반응형

- 스프링에서 의존성 주입을 어떻게 할까?
- XML을 이용한 의존성 주입(DI)은 어떻게 할까?
의존성 주입은 어떻게 하는걸까?
스프링에서 의존성 주입(DI) 방법은 XML 설정을 통한 방법과 어노테이션을 이용한 방법이 있다.
XML 설정을 통한 의존성 주입은 설정 파일에서 일괄적으로 의존성을 주입을 설정할 수 있기 때문에 주로 외부 라이브러리 클래스를 주입해야할 경우에 사용한다.

어노테이션을 통한 의존성 주입은 주로 클래스간에 의존 관계를 주입할 때 사용한다.
XML 설정을 통한 의존성 주입
생성자를 이용한 주입 방법
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id="ticket" class="model.AsianaTicket" lazy-init="true"></bean>
<bean id="personService" class="model.PersonService">
<constructor-arg>
<value>김철수</value>
</constructor-arg>
<constructor-arg>
<ref bean="ticket"/>
</constructor-arg>
</bean>
</beans>
- lazy-init = "true" : 생성 지연, Bean 객체를 사용할 때 생성
- (default : WAS에서 Context load시에 Bean 객체로 등록)
- <constructor-arg> : Class의 생성자를 이용해 의존성을 주입한다.
- ref : Root Web Application context에서 정의된 객체 이름
Setter를 이용한 주입 방법
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id = "ticket" class="model.KalTicket"></bean>
<bean id = "personService" class="model.PersonService">
<property name="name">
<value>홍길동</value>
</property>
<property name="ticket">
<ref bean="ticket"/>
</property>
</bean>
</beans>
- <property> : 클래스의 Setter 메서드를 이용해 의존성을 주입한다.
- name : 호출할 Setter
- <ref> : Root Web Application context에서 정의된 객체 이름
Spring IOC Container는 이 설정 정보를 로딩하여 설정대로 Bean(ex - personService)을 생성해 관리한다.
getBean()을 통해 의존대상 확보
그 후, 애플리케이션에서 필요한 시점에 getBean()하면 싱글톤 방식으로 개별 객체를 반환해준다.
어플리케이션에서 getBean()를 호출하면 IoC 컨테이너는 호출된 Bean에 대한 DL(Dependency Lookup)을 진행하며 검색을 통해 의존대상을 확보한다.
public class TestIOC {
/**
* IOC (DL, DI)를 테스트하는 예제
* @param args
*/
public static void main(String[] args) {
// 설정대로 개별 객체들을 메모리에 생성
ClassPathXmlApplicationContext factory = new ClassPathXmlApplicationContext("spring-config.xml");
// Dependency Lookup : 검색 lookup을 통해 의존대상을 확보
PersonService service = (PersonService)factory.getBean("personService");
System.out.println(service.getName());
service.getTicket().ticketing();
factory.close();
}
}
이때, IoC 컨테이너는 싱글톤 방식으로 Bean을 관리하기 때문에, getBean()을 통해 받은 객체의 주소는 모두 같다.

반응형
'Develop' 카테고리의 다른 글
| [디자인 패턴] 싱글톤 디자인 패턴(Singleton Design Pattern) (0) | 2022.04.28 |
|---|---|
| [Spring] properties 파일을 이용한 DI (0) | 2022.04.27 |
| [Spring] @Autowired, @Resource, @Inject의 차이 (0) | 2022.04.26 |
| [Spring] 의존성과 의존성 주입 (Dependency & Dependency Injection) (0) | 2022.04.26 |
| [Spring] IoC 제어 방식 (Inversion of Control) (0) | 2022.04.25 |