스프링 빈 초기화에 관한 한 가지 질문이 있습니다. init 메서드를 통해 빈 속성을 채울 때 scneario는 무엇이 될까요? 아래 코드 스 니펫을 살펴보십시오. 여기에서는 init 메소드를 통해 수퍼 클래스 빈 프라퍼티 목록을 채 웁니다.초기화 메서드를 통한 스프링 빈 특성 채우기
1) 수퍼 클래스 콩 :
public class Super {
private List<String> list = new ArrayList<String>();
public void setList(List<String> list) {
this.list = list;
}
public void init(){
System.out.println("Super init called");
populateList();
System.out.println("Super list"+list.size());
}
public void populateList(){
list.add("A");
list.add("B");
}
public List<String> getList() {
return list;
}
}
2) 콩 2
public class Sub extends Super {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appXml/init-test.xml");
Sub utils = (Sub)ctx.getBean("sub");
System.out.println("Sub list:::"+utils.getList().size());
for(String s : utils.getList()){
System.out.println("Value::::" +s);
}
}
}
3) 스프링 컨텍스트 XML :
<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-3.0.xsd">
<bean id = "super" class = "com.hitesh.springtest.Super" init-method="init">
</bean>
<bean id = "sub" class = "com.hitesh.springtest.Sub"></bean>
</beans>
4) 출력 : 슈퍼 INIT 전화 번호 수퍼 list2 하위 목록 ::: 0
제 질문은 컨테이너에 의해 수퍼 클래스가 초기화되고 init()이 호출되는 것입니다. 이 메서드에서는 목록 개체가 채워집니다. 이제 하위 클래스 인스턴스화가 완료되면 왜 목록 크기가 0으로 설정되는지, 수퍼 bean 초기화에 채워진 매우 동일한 목록 객체를 참조하기 때문에 누군가가 이것을 설명 할 수 있습니까? 봄이 id = "super"
와 bean
를 작성하고 당신의 Spring-context.xml
에 정의 된대로 그것을 만들 때는 init-method
를 호출 있기 때문에
다음과 같은 내용을 놓쳤습니다 : '우리는 슈퍼 빈 초기화로 채워진 매우 동일한 목록 객체를 참조합니다.' –