2016년 9월 19일 월요일

[자바교육,스프링교육추천◆탑크리에듀]#20.ApplicationContext의 분리(부모, 자식)

#20.ApplicationContext의 분리(부모, 자식)
ApplicationContext 분리(부모자식)

n  한 컨텍스는 다른 컨텍스트의 부모가 될 수 있다자식 컨텍스에 있는 빈이 부모 컨텍스트에 있는 빈 참조 가능한데 스프링은ApplicationContext 중첩 기능을 제공 함으로서 설정을 여러 파일로 나눌 수 있게 해준다자식 컨텍스트에서 부모 컨텍스트의 빈을 참조하는 방식은 동일하다단 이름이 같은 것이 있다면 ref 태그에서 parent 속성을 사용하면 된다.

[parent.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-4.2.xsd">

<bean id="parent1" class="java.lang.String">
<constructor-arg>
<value>parent bean 1</value>
</constructor-arg>
</bean>

<bean id="parent2" class="java.lang.String">
<constructor-arg>
<value>parent bean 2</value>
</constructor-arg>
</bean>
</beans>

[child.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-4.2.xsd">

<bean id="target1" class="onj.context.overlap.Onj">
<property name="val1">
<ref bean="parent1"/>
</property>
</bean>

<bean id="target2" class="onj.context.overlap.Onj">
<property name="val2">
<ref parent="parent2"/> <!– 부모 context에서 parent2라는 id,name을 검색 à
</property>
</bean>

<bean id="parent2" class="java.lang.String">
<constructor-arg>
<value>child bean 2</value>
</constructor-arg>
</bean>
</beans>

[Onj.java]
package onj.context.overlap;

public class Onj {
private String val1;
private String val2;

public String getVal1() {
           return val1;
}
public void setVal1(String val1) {
         this.val1 = val1;
}
public String getVal2() {
           return val2;
}

public void setVal2(String val2) {
           this.val2 = val2;
}
}

[ContextOverlapExam.java]
package onj.context.overlap;
import org.springframework.context.support.GenericXmlApplicationContext;
public class ContextOverlapExam {
public static void main(String[] args) {
GenericXmlApplicationContext parent = new GenericXmlApplicationContext();
parent.load("classpath:parent.xml");
parent.refresh();

GenericXmlApplicationContext child = new GenericXmlApplicationContext();
child.load("classpath:child.xml");
child.setParent(parent);
child.refresh();

Onj target1 = (Onj) child.getBean("target1");
Onj target2 = (Onj) child.getBean("target2");
String target3 = (String) child.getBean("parent2");

System.out.println(target1.getVal1());
System.out.println(target2.getVal2());
System.out.println(target3);
}
}

댓글 없음:

댓글 쓰기