Learn Spring - Bean Scope属性之singleton和prototype
Posted
Scope属性
Spring Bean配置中的Scope属性用于告诉Ioc容器创建Bean对象的范围,只能创建一个对象还是能够创建任意个对象。其值可以是singleton、prototype、request、session和global-session。request、session和global-session只有在web应用中才有效。这里只讲prototype和singleton。
singleton和prototype区别
| singleton | prototype |
|---|---|
| 只能创建一个Bean实例,Ioc容器会对创建的实例进行缓存,下次请求创建时,返回缓存的实例 | 可以创建任意个实例 |
| 默认值 | 非默认值 |
Singleton
目录结构

Code
HelloSpring.java
package me.coolcodes;
public class HelloSpring {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
Main.java
package me.coolcodes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloSpring objA = (HelloSpring) context.getBean("helloSpring");
objA.setMessage("I am objA");
objA.getMessage();
HelloSpring objB = (HelloSpring) context.getBean("helloSpring");
objB.getMessage();
}
}
先通过getBean()创建一个objA,设置message为I am objA。然后再通过getBean()创建一个objB。如果objA和objB是不同的对象,最后输出应该是I am objA \n Hello World!。反之,如果是同一个对象,最后输出应该是I am objA \n I am objA。
Beans.xml
设置scope为singleton
<?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 = "helloSpring" class = "me.coolcodes.HelloSpring" scope="singleton">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
结果

从结果可以看出,objA和objB是同一个对象。
Prototype
只需要将Beans.xml中scope的值改为prototype
结果

从结果可以看出,objA和objB是不同的对象。