2013-06-10 4 views
0

스프링 빈 초기화에 관한 한 가지 질문이 있습니다. 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를 호출 있기 때문에

답변

0

당신은 "슈퍼리스트 2"를 참조하십시오.

스프링이 bean id = "sub"을 만들 때 지정되지 않았기 때문에 init-method을 호출하지 않습니다. sub 빈의 정의에 init-method을 추가하면 기대하는 동작을 보게됩니다.

+0

다음과 같은 내용을 놓쳤습니다 : '우리는 슈퍼 빈 초기화로 채워진 매우 동일한 목록 객체를 참조합니다.' –

3

very same list object이 아닙니다. 문맥에는 두 개의 객체 인 supersub이 있습니다. list은 인스턴스 필드이므로 list 개체의 인스턴스가 두 개 있습니다. 하나는 super이고 다른 하나는 sub입니다. sub에 대한 값은 해당 빈에 대해 init-method이 설정되지 않았기 때문에 초기화되지 않았습니다.

1

당신이 (스프링 컨테이너의 라인에 느슨하게 ) 개체를 초기화하는 대신 봄의 말할 수 있습니다, 코드 그래서 두 개의 서로 다른 개체가이

Super super = new Super(); 
super.init(); 

Sub sub = new Sub(); 

//now if you say 
sub.getList().size(); 
//This will always print size zero as you never initialized the super class collection. 

과 같을 것입니다. 또 다른 bean으로 정의 된 경우, Spring은 수퍼 클래스의 특성을 상속받지 않습니다.

관련 문제