bean的作用域
用于确定Spring创建bean实例的个数
默认为singleton
可以用scope进行配置
scope取值
我们常用的:
singleton:单例模式(servlet)
prototype:多例,即执行一次getBean便获得一个实例.(struct-action)
测试
测试流程
Users类
xml配置
junit测试
修改xml文件bean的scope
junit
singleton
Users类
package com.scx.scope.test;
public class Users {
private Integer uid;
private String username;
private Integer age;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
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.xsd">
<bean id="UsersId" class="com.scx.scope.test.Users" scope="singleton"></bean>
</beans>
junit测试
package com.scx.scope.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void testScope() {
String xmlPath = "com/scx/scope/test/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
xmlPath);
Users user1 = applicationContext.getBean("UsersId", Users.class);
Users user2 = applicationContext.getBean("UsersId", Users.class);
System.out.println(user1);
System.out.println(user2);
System.out.println(user1==user2);
}
}
运行结果
两次输出的结果一样 ,为单例模式
prototype
修改xml文件bean的scope为prototype
<bean id="UsersId" class="com.scx.scope.test.Users" scope="prototype"></bean>
运行结果:
两次输出的结果不同,为多例
由此可以知道可以通过对scope的设置来确定生成bean的方式。