본문 바로가기
Programming/Spring

[spring] DI(Dependency Inversion) 개념

by NAMP 2016. 4. 19.

[spring] DI(Dependency Inversion) 개념

Dependency 관계

Dependency 관계란 Bean 과 Bean의 결합관계다.

Context 가 만들어질 때 applicationContext.xml 환경설정 파일을 읽어들인다.

Dependency 의 구현방법에는 두 가지가 있다.

첫째는 Dependency Lookup 이다.

컨테이너가 callback을 통해서 제공하는 Lookup Context를 이용해서 필요한 리소스나 오브젝트를 얻는 방식. EJB 와 Apache Avalon 의 구현방법

둘째는 Dependency Injection 이다.

비즈니스 오브젝트에 Lookup 코드를 사용하지 않고 컨테이너가 직접 의존구조를 오브젝트에 설정할 수 있도록 지정해주는 방법. Setter Injection 과 Constructor Injection 으로 나뉜다.

Dependency Lookup

Spring 에서 Dependency Lookup 을 이용하기 위해서는 해당 Bean 이 XML 설정파일에 등록 되어 있어야 한다.
객체의 getBean() 메소드를 호출하면서 얻고자 하는 Bean의 이름값을 넘겨준다.

UserService us = (UserService)factory.getBean(“userService”);

Dependency Injection

Dependency Injection 이란?

Dependency Injection 은 각 Bean 사이의 의존관계 설정을 XML 설정파일에 등록된 정보를 바탕으로 컨테이너가 자동적으로 연결해 주는 것.
프로그램 코드에서 직접 필요한 Bean 을 생성하지 않고 컨테이너가 자체적으로 해당 Bean 에서 필요한 객체를 넘겨줘서 사용하는 방식

레퍼런스는 ref, 기본값은 value 로 넘긴다.

Constructor Injection

Spring 에서는 Bean을 초기화 시키기 위해 default 생성자를 호출한다.
Contructor Injection 을 사용하면 생성자의 매개변수로 Dependency 설정 내용을 넘겨주는 것이므로 Bean 클래스 작성시 매개변수를 가지는 생성자가 있어야 한다.

매개변수 Type 매핑

Constructor Injection 을 이용할 때 생성자에 하나의 값만 설정하는 게 아니라 여러 값을 한꺼번에 설정하고자 하는 경우, <constructor-arg> 태그를 여러 개 사용한다.

<bean id=”userVO” class=”com.uservo” >
    <constructor-arg value=”홍길동”/>
    <constructor-arg value=”19”/>
</bean>

Setter Injection

Bean 이 가지고 있는 Setter 메소드를 호출하여 Dependency 를 설정하는 방법

<bean id=”userService” class=”com.UserServiceImpl” />
    <property name=”userDAO” ref=”userDAO”/>
</bean>
<bean id=”userDAO” class=”com.UserDAO” />

setUserDAO 메소드가 있어야 한다.

Setter Injection 과 Constructor Injection 동시 사용

Dependency 를 이용할 때 Constructor Injection 과 Setter Injection을 동시에 한 Bean 에 설정하여 사용할 수 있다.

Setter Injection vs Constructor Injection

Setter : 사용하려는 Bean 이 실제 기능 구현 시 사용될 수도 있고, 아닐 수도 있을 때 이 방식을 사용하는 것이 좋다.

Constructor : 사용하려는 외부 Bean 이 자신의 내부에서 반드시 사용되는 경우

집합객체 설정

컬렉션을 많이 사용한다.

집합객체

list, set, map, props

List 타입 매핑

Set 타입 매핑

Map 타입 매핑

Properties 타입 매핑

의존 관계 자동 설정

autowire 속성

Spring 프레임워크에서는 XML 기반의 Spring 설정파일을 간단하고 쉽게 작성할 수 있도록 Bean 설정을 자동으로 처리할 수 있는 방법을 제공한다.
XML 설정파일에 모든 Dependency 관계를 설정하지 않고 Spring 프레임워크에서 자체 판단해서 Bean 객체를 생성하고 Dependency Injection 을 제공해 주는 방식

byType 사용

<bean id="service" class="user.service.UserServiceImpl" autowire="byType" />

같은 타입이 하나이어야만 한다.
동일 타입이 여러 개 있으면 에러 발생

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'service' defined in class path resource [applicationContext.xml]: Unsatisfied dependency expressed through bean property 'dao': : No qualifying bean of type [user.dao.UserDAO] is defined: expected single matching bean but found 4: jdbc,spring,ibatis,mybatis; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [user.dao.UserDAO] is defined: expected single matching bean but found 4: jdbc,spring,ibatis,mybatis

byName

<bean id="service" class="user.service.UserServiceImpl" autowire="byName" />

dao 라는 이름을 찾아서 주입한다.

    <bean id="dao" class="user.dao.UserDAO_JDBC"></bean>
    <bean id="service" class="user.service.UserServiceImpl" autowire="byName" />

constructor 사용

autodetect 사용


'Programming > Spring' 카테고리의 다른 글

[spring] DI 관련 Source 내용  (0) 2016.04.20
[spring] 데이터베이스 연동  (0) 2016.04.19
[Spring] 설정 파일  (0) 2016.04.18
[Spring] IoC(Inversion of Controller) 컨테이너  (0) 2016.04.18
[spring] 프레임워크 개요  (0) 2016.04.17

댓글