Spring XML을 이용한 설정

2012. 8. 16. 17:09OpenSource/Spring

반응형
스프링의 애플리케이션 컨텍스트는 XML에 담긴 DI정보를 활용 할 수 있다.

DI 정보가 담긴 XML 파일은 <beans>를 루트 엘리먼트로 사용한다.
<beans>는 이름에서도 알 수 있듯이 여러개의 <bean>을 정의 할 수 있다.

아래의 그림처럼 http://acet.pe.kr/120  에서의 @configuration과 @bean을 각 @configuration을 <beans>
@bean을 <bean>이라고 대응해서 생각하면 더 쉬울 것 이다.

[참고 그림]


클래스 설정과 xml설정의 대응항목
   자바 코드 설정정보  XML 설정정보
 빈 설정파일  @Configuration  <beans>
 빈의 이름  @Bean methodName()  <bean id="methodName"
 빈의 클래스  return new BeanClass();  class="a,b,c...BeanClass">

ex) connectionMaker()메소드의 <bean> 태그 전환
@Bean   --------------------------------> <bean
pubilc ConnectionMaker
    connectionMaker(){ -------------------> id="connectionMaker"
         return new DConnectionMaker(); ----> class="springbook...DConnectionMaker" />
    }


※ <property> 태그를 사용해 의존 오브젝트와의 관계를 정의 해보자.
<property> 태그는 name과 ref라는 두개의 애트리뷰트를 갖는다.
name은 애트리뷰트의 이름이다. 이 프로퍼티 이름으로 수정자 메소드를 알 수 있다.
ref는 수정자 메소드를 통해 주입해줄 오브젝트 빈 이름이다.

ex) userDao.setConnectionMaker(connectionMaker()); 를 아래와 비교해보라.
<property name="connectionMaker" ref="connectionMaker" />

<property> tag를 <baen> tag안에 넣어주면 된다.
ex)
     <bean id="userDao" class="springbook.dao.UserDao">
             <property name="connectionMaker" ref="connectionMaker" />
      </bean>

이첨럼 <bean> tag를 이용해 @Bean 메소드를 모두 xml로 변환 했다.
마지막으로 <beans> tag로 감싸주면 된다.
ex)
<beans>
    <bean id="connectionMaker" class="springbook.user.dao.DConnectionMaker" />
    <bean id="userDao" class="springbook.dao.UserDao">
          <property name="connectionMaker" ref="connectionMaker" />
    </bean>
</beans>

※ <property> tag의 name과 ref는 그 의미가 다르므로 이름이 같더라도 어떤 차이가 있는지 구별 할 수 있어야 한다.
name 애트리뷰트DI에 사용할 수정자 메소드의 프로퍼티 이름이며, ref 애트리뷰트주입할 오브젝트를 정의한 빈의 ID(DI 받을 빈을 지정) 이다. 보통 프로퍼티이름과 DI되는 빈의 이름이 같은 경우가 많다.

반응형