2016-09-22 5 views
1

XML 스프링의 싱글 톤 범위가 작동하지 않습니다. 프로토 타입 작업이 아닙니다. 범위 태그 프로토 타입이 없어도 작동합니다.xml의 빈 범위가 작동하지 않습니다.

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-3.0.xsd"> 

    <bean id="restaurant" class="bean_scope.Restaurant1" scope="singleton">   <!-- scope="singleton" --> 
    </bean> 

</beans> 
setter 메소드에 대한

자바 클래스 :

package bean_scope; 

public class Restaurant1 { 

    private String welcomeNote; 

    public void setWelcomeNote(String welcomeNote) { 
     this.welcomeNote = welcomeNote; 
    } 

    public void greetCustomer(){ 
     System.out.println(welcomeNote); 
    } 
} 

자바 봄 테스트 클래스 :

package bean_scope; 

import org.springframework.context.support.ClassPathXmlApplicationContext; 

public class Restaurant1Test { 

    public static void main(String[] args) { 

     Restaurant1 restaurantOb1=(Restaurant1) new ClassPathXmlApplicationContext("bean_scope/SpringConfig1.xml") 
      .getBean("restaurant"); 
     restaurantOb1.setWelcomeNote("Welcome"); 
     restaurantOb1.greetCustomer(); 

     Restaurant1 restaurantOb2=(Restaurant1) new ClassPathXmlApplicationContext("bean_scope/SpringConfig1.xml") 
      .getBean("restaurant"); 
     //restaurantOb2.setWelcomeNote("Hello"); 
     restaurantOb2.greetCustomer(); 
    } 

} 

출력 :

Welcome 
null 

싱글 톤 범위가 작동하지 않는 이유는 무엇입니까?

+1

내가 여기 어떤 문제를 볼니까. 두 개의 응용 프로그램 컨텍스트를 작성 중이므로 두 개의 Restaurant Bean이 작성됩니다. –

답변

0

두 개의 독립 인스턴스 ClassPathXmlApplicationContext을 만들면 각 인스턴스마다 고유 한 싱글 톤 인스턴스가 생성됩니다. singleton 범위는 스프링 컨텍스트 내에 콩 의 인스턴스가 하나만 있다는 것을 의미합니다. 그러나 두 개의 컨텍스트가 있습니다.

이것은 당신이 기대하고있는 결과를 얻을 것이다 :

ApplicationContext ctx = new ClassPathXmlApplicationContext("bean_scope/SpringConfig1.xml"); 

Restaurant1 restaurantOb1=(Restaurant1) ctx.getBean("restaurant"); 
restaurantOb1.setWelcomeNote("Welcome"); 
restaurantOb1.greetCustomer(); 

Restaurant1 restaurantOb2=(Restaurant1) ctx.getBean("restaurant"); 
//restaurantOb2.setWelcomeNote("Hello"); 
restaurantOb2.greetCustomer(); 
관련 문제