xml中的bean范围无法正常工作

时间:2016-09-22 08:25:39

标签: spring

XML中的单例bean范围弹簧无法正常工作。只有原型工作。即使没有任何范围标记原型也能正常工作。

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方法的Java类:

package bean_scope;

public class Restaurant1 {

    private String welcomeNote;

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

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

Java Spring Test类:

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 个答案:

答案 0 :(得分:0)

由于您创建了两个独立的ClassPathXmlApplicationContext实例,每个实例都有自己的bean单例实例。 singleton范围意味着在Spring上下文中只有一个bean 的实例 - 但是你有两个上下文。

这会产生您期望的结果:

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();