나의개발일지
Spring) DI 의존성 주입 본문
DI ( Dependency Injection )
객체 간의 의존관계를 자신이 아닌 외부의 조립기가 수행한다. DI를 통해 시스템에 잇는 각 객체를 조정하는 외부 개체가 객체들에게 생성시에 의존관계를 주어진다
느슨한 결합의 주요 강점 : 객체는 인터페이스에 의한 의존 관계만을 알고 있으며, 이 의존 관계는 구현 클래스에 대한 차이를 모르는 채 서로 다른 구현으로 대체가 가능하다.
빈 생성 범위
싱글톤 빈 ( Singleton Bean )
- 스프링 빈은 기본적으로 'singleton'으로 만들어짐
- 그러므로, 컨테이너가 제공하는 모든 빈의 인스턴스는 항상 동일함
- 컨테이너가 항상 새로운 인스턴스를 반화하게 만들고 싶을 경우 scope를 'prototype' 으로 설정해야 한다.
빈의 생성 범위 지정
범위 | 설명 |
singleton | 스프링 컨테이너당 하나의 인스턴스 빈만 생성 (default) |
prototype | 컨테이너에 빈을 요청할 때마다 새로운 인스턴스 생성 |
request | HTTP Request별로 새로운 인스턴스 생성 |
session | HTTP Session별로 새로운 인스턴스 생성 |
DI - XML
기본 설정 - 빈 객체 생성 및 주입
주입할 객체를 설정파일에 설정
<bean> : 스프링 컨테이너가 관리할 Bean객체를 설정
기본 속성
- name : 주입 받을 곳에서 호출 할 이름 설정
- id : 주입 받을 곳에서 호출 할 이름 설정
- class : 주입 할 객체의 클래스
- factory-method : Singleton 패턴으로 작성된 객체의 factory 메소드 호출
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- HelloWorld 클래스를 빈으로 등록 -->
<bean id="helloWorld" class="com.example.HelloWorld"/>
<!-- HelloMessage 클래스를 빈으로 등록 -->
<bean id="helloMessage" class="com.example.HelloMessage"/>
</beans>
기본설정 - 빈 객체 얻기
설정 파일에 설정한 bean을 Container가 제공하는 주입기 역할의 api를 통해 주입 받는다.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// HelloWorld 빈 객체를 가져옴
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
Constructor injection
객체 또는 값을 생성자를 통해 주입 받는다
<constructor-arg> : <bean>의 하위 태그로 설정한 bean 객체 또는 값을 생성자를 통해 주입하도록 설정
설정 방법 : <ref>, <value>와 같은 하위태그를 이용하여 설정 하거나 또는 속성을 이용하여 설정
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- HelloMessage 클래스를 빈으로 등록하고 생성자 주입을 사용하여 HelloMessage 빈을 HelloWorld 빈에 주입 -->
<bean id="helloMessage" class="com.example.HelloMessage">
<!-- 생성자 주입을 통해 HelloWorld 빈을 주입 -->
<constructor-arg ref="helloWorld"/>
</bean>
<!-- HelloWorld 클래스를 빈으로 등록 -->
<bean id="helloWorld" class="com.example.HelloWorld"/>
</beans>
Property injection
property를 통해 객체 또는 값을 주입 받는다. - setter method
※주의 : setter를 통해서는 하나의 값만 받을 수 있다.
<preoperty> : <bean>의 하위태그로 설정한 bean 객체 또는 값을 property를 통해 주입하도록 설정
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- HelloMessage 클래스를 빈으로 등록하고 property injection을 사용하여 HelloWorld 빈을 주입 -->
<bean id="helloMessage" class="com.example.HelloMessage">
<!-- property injection을 통해 HelloWorld 빈을 주입 -->
<property name="helloWorld" ref="helloWorld"/>
</bean>
<!-- HelloWorld 클래스를 빈으로 등록 -->
<bean id="helloWorld" class="com.example.HelloWorld"/>
</beans>
DI - Annotation
빈으로 사용될 클래스에 annotation (@Autowired)를 부여해 주면 자동으로 빈 등록 가능.
" 오브젝트 빈 스캐너 " 로 "빈 스캐닝"을 통해 자동 등록
- 빈 스캐너는 기본적으로 클래스 이름을 빈의 아이디로 사용 ( 클래스의 이름의 첫글자만 소문자로 바꾼것)
스테레오(Stereotype) 어노테이션은 Spring 프레임워크에서 사용되는 메타 어노테이션으로, 다른 어노테이션들을 한데 묶어서 특정 컴포넌트나 클래스를 표시하는 역할을 한다.
Stereotype annotation 종류
Stereotype | 적용대상 |
@Repository | Data Access Layer의 DAO 또는 Repository 클래스에 사용 DataAccessException 자동변환과 같은 AOP의 적용 대상을 선정하기 위해 사용 |
@Service | Service Layer의 클래스에 사용 |
@Controller | Presentation Layer의 MVC Controller에 사용 스프링 웹 서블릿에 의해 웹 요청을 처리하는 컨트롤러 빈으로 선정 |
@Component | 위의 Layer 구분을 적용하기 어려운 일반적인 경우에 설정 |
스프링 빈 의존 관계 설정
스프링 빈 의존 관계설정을 할때 Annotation을 사용할 수도 있다.
annotation | 설명 |
@Resource | 맴버변수, setter method에 사용 가능 타입에 맞춰서 연결 |
@Autowired | Required 속성을 통해 DI여부 조정 맴버 변수, setter, constructor, 일반 method 사용 가능 타입에 맞춰서 연결 |
@Inject | Javax.inject-x.x.x.jar 라이브러리 필요 맴버 변수, setter, constructor, 일반 method 사용 가능 이름으로 연결 |
기본설정 - 빈 객체 얻기
설정한 COmponent-scan에 의해 Scanning 된 bean을 Container가 제공하는 주입기 역할의 API를 통해 주입 받는다.
bean 파일에는 @Component 설정
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class HelloMessage {
// HelloWorld 객체를 필드로 가짐
private HelloWorld helloWorld;
// @Autowired 어노테이션을 사용하여 의존성 주입
@Autowired
public void setHelloWorld(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
}
public String helloKor(String str) {
// 처리 로직을 작성
return "안녕하세요, " + str + "!";
}
}
스프링 빈 의존 관계 설정
필드에 @Autowired 적용
- 동일한 타입의 bean이 여러 개일 경우에는 @Qualifier("name")으로 식별한다.
생성자에 @Autowired 적용
- immutable : 의존성이 필요한 FIeld를 final로 선언 가능
- 순환 참조 방지
- 생성자가 1개일 경우 @Autowired 생략 가능
- 동일한 타입의 bean이 여러 개일 경우에는 @Qualifier("name")으로 식별한다.
'Back-End > Spring' 카테고리의 다른 글
Spring) Interceptor (0) | 2024.04.19 |
---|---|
Spring) AOP (0) | 2024.04.17 |
Spring) IoC & Container (0) | 2024.04.15 |
Spring) SpringMVC (1) | 2024.01.04 |
Spring) Row Mapper (1) | 2023.12.18 |