XML spring中的单例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
请帮助我为什么单例作用域不工作
由于您创建了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();