Bean的作用域有如下几个:
(1)、singleton:单例,在一个Bean容器中只存在一份
(2)、prototype:每次使用创建新的实例,destroy方式不生效
(3)、request:每次http请求创建一个实例且仅在当前request内有效
(4)、session:每次http请求创建,当前session内有效
(5)、global session:基于portlet的web中有效(portlet定义了global session),如果在web中,跟session一样。
(一)作用域:singleton
1、我们写个测试案例:我们新建一个BeanScope.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 = "beanScope" class = "com.yuna.scope.BeanScope" scope="singleton">
</bean>
</beans>
2、新建BeanScope类,只有个简单的输出方法,我们可以根据hashcode的值来看看,在不同的作用域中其值有什么不一样
public class BeanScope {
public void say() {
System.out.println("hashcode 是不是一致呢:" + this.hashCode());
}
}
3、写个测试类TestBeanScope
public class TestBeanScope extends UnitTestBase{
public TestBeanScope() {
super("classpath:BeanScope.xml");
}
@Test
public void testSingleton() {
BeanScope bScope = super.getBean("beanScope");
bScope.say();
BeanScope bScope2 = super.getBean("beanScope");
bScope2.say();
}
//我们测试scope="singleton"时,可以看出bScope.say()和bScope2.say()打印的值是一致的,但是,若是写两个测试方法,一个是 testSingleton() ,一个是 testSingleton2(),此时他们打印的 bScope.say()方法打印的hashcode值是不一样的,这是由于单元测试的原因,单元测试时每个方法执行前会先调用UnitTestBase类的before()方法,然后再执行destory()方法
}
(二)作用域:prototype
1、我们将刚才的BeanScope.xml中的scope改成prototype
<?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" >
<!--作用域是singleton -->
<!-- <bean id = "beanScope" class = "com.yuna.scope.BeanScope" scope="singleton">
</bean> -->
<!--作用域是prototype -->
<bean id = "beanScope" class = "com.yuna.scope.BeanScope" scope="prototype">
</bean>
</beans>
2、在测试类中写个testPrototype方法,然后一起运行,可以看到打印的hashcode值是不一样的
@Test
public void testPrototype() {
BeanScope bScope = super.getBean("beanScope");
bScope.say();
}