Computer Science/Spring

#2 Spring DI - xml 기반

꿈꾸는어린이 2018. 5. 14. 14:24


Spring DI

<BR>

Spring Container

  • Spring Bean 객체의 life-cycle관리(bean 객체 생성, 초기화, 이용, 삭제)

  • DI (Dependency Injection) : bean들간 의존 관계에 따라 객체들을 연결

  • 가장 많이 쓰는 interface : ApplicationContext (BeanFactory를 확장)

  •   ApplicationContext context = new ClassPathXmlApplicationContext(test.xml);
    BeanType bean = context.getBean("beanName", test.class);


<BR>

bean 생성

  • <beans> : 설정 파일의 root element

  • <bean> : container에 의해 생성/관리될 bean 객체를 정의

  
<bean id="duke" class="com.spring.springIdol.Juggler"/>
//bean 객체 정의

Performer performer = (Performer)context.getBean("duke");
//container로부터 특정 bean 객체의 참조를 가져옴


의존관계 설정 - 생성자 방식

  • constructor injection, 생성자 통해 의존 객체 주입

  • <constructor-arg> 이용하여 설정

  public class Instrumentalist implements Performer {
 private String song;
 private Instrument instrument;
 
 //생성자
 public Instrumentalist(String song, Instrument instrument){
   this.sont = song;
   this.instrument = instrument;
}


//xml 설정 파일
<bean id="kenny" class="com.springinaction.springidol.Instrumentalist">
<constructor-arg value="Jingle Bells"/>
<constructor-arg ref="saxophone"/>
</bean>
  • 가장 근접한 type의 parameter 가진 생성자 선택

  • <value>로 전달된 값은 String type으로 간주, int type으로 넘기려면

    <constructor-arg value="10" type="int" />

  • "c" namespace 이용

      
    <bean id="kenny" class="com.springIdol.Instrumentalist"
    c:song = "Jingle bells"
    c:instrument-ref = "saxophone" />

의존관계 설정 - property 방식

  • property에 대한 setter method를 통해 의존 객체 주입

  • setter 정의되어 있어야 하고 기본 생성자도 존재해야 함(객체 생성 후 setter통해 주입되므로)

  • <property> 태그 사용

  public class Instrumentalist implements Performer {
public Instrumentalist() {} //기본 생성자

private String song;
public void setSong(String song) {
this.song = song;
}

private Instrument instrument;
public void setInstrument(Instrument instrument) {
this.instrument = instrument;
}
}

//xml설정 파일
<bean class="com.springinaction.springidol.Instrumentalist" id="kenny">
<property name="song" value="Jingle Bells"/>
<property name="instrument" ref="saxophone"/>
</bean>
  • "p" namespace 사용

    <bean class="com.springinaction.springidol.Instrumentalist" id="kenny"

    p:song = "Jingle Bells"

    p:instrument-ref = "saxophone" />



Collection wiring

  • bean property가 collection type(list, set, map등)인 경우

  • <property>의 자식으로 사용

  <bean id="springIdol" class="com.springinaction.springidol.SpringIdol">
<property name="performers">
<list>
<ref bean="duke"/>
<ref bean="kenny"/>
</list>
</propety>
</bean>


List type

  <bean id="hank" class="com.springinaction.springidol.OneManBand">
<property name="instruments">
<list>
<ref bean="guitar"/>
<ref bean="cymbal"/>
</list>
</propety>
</bean>


//OneManBand class
public class OneManBand implements Performer{
 private Collection<Instrument> instruments;
 public void setInstrument(Collection<Instrument instruments){
   this.instruments = instruments;
}
}
  • set 타입도 동일. 다만 set타입은 중복된 값 제거하고 전달(중복 x)


Map type

  <bean id="hank" class="com.springinaction.springidol.OneManBand">
<property name="instruments">
<map>
<entry key="GUITAR" value-ref="guitar"/>
<entry key="CYMBAL" value-ref="cymbal"/>
</map>
</propety>
</bean>


//OneManBand class
public class OneManBand implements Performer{
...
private Map<String, Instrument> instruments;
public void setInstruments(Map<String,Instrument> instruments){
  this.instruments = instruments;
}


for(String key : instrument.keySet()){
  System.out.print(key);
  Instrument instrument = instruments.get(key);
  instrument.play();
}

}
  • key, value 모든 타입이나 객체 가능

  • <entry> 속성으로 key-ref, value-ref 속성 사용


properties type

  • key와 value가 모두 String 인 map과 같다

  <bean id="hank" class="com.springinaction.springidol.OneManBand">
<property name="instruments">
<props>
<prop key="GUITAR">STRUM STRUM STRUM</prop>
<prop key="CYMBAL">CRASH CRASH CRASH</prop>
</props>
</propety>
</bean>


//OneManBand class
public class OneManBand implements Performer{
...
private Properties instruments;
public void setInstruments(Properties instruments){
  this.instruments = instruments;
}


for(Iterator iter = instruments.keySet().iterator(); iter.hasNext()){
  String key = (String)iter.next();
  System.out.println(key+instruments.getProperty(key));
}

}


SpEL 이용한 DI 설정

  • Spring Expression Language

  • #{...} 형식

  <property name="count" value="#{5}" />
<property name="song" value="#{kenny.song}" />
// song이 private이면 getSong()으로 호출해야함
<property name="random" value="#{T(java.lang.Math).random()}" />

'Computer Science > Spring' 카테고리의 다른 글

#5 Spring MVC 구조  (0) 2018.05.25
#4 Bean 객체의 life-cycle 관리  (0) 2018.05.14
#3 Spring DI : auto-wiring, annotation 기반  (0) 2018.05.14
#1 Spring Framework  (0) 2018.05.13
Maven(메이븐)이란?  (0) 2018.03.12