您的位置:首页 > 编程语言 > Java开发

spring bean的形式(3)

2017-01-18 14:46 316 查看
一、spring bean的作用域分为以下五种:

1、singleton(默认模式):单例,指一个bean容器中只存在一份

2、prototype:每次请求(每次使用)创建新的实例,destroy方式不生效

3、request:每次http请求创建一个实例且仅在当前request内有效

4、session:同上,每次http请求创建,当前session中有效

5、global session:基于portlet的web中有效(portlet定义了global sessio),如果在web中,同session

二、配置bean的作用域

schema配置方式:

<!-- 设置bean的作用域scope属性值为prototype,默认为singleton,可以不设置scope属性 -->
<bean name="beanScope" class="com.jsun.test.springDemo.BeanScope" scope="prototype"></bean>


annotation注解方式:

<!-- 配置自动扫描 -->
<context:component-scan base-package="com.jsun.test"></context:component-scan>

//注册bean
@Component("beanScope")
//设置bean的作用域范围为prototype
@Scope("prototype")
public class BeanScope {

}


单元测试打印出bean的hashCode值进行验证:

@Test
public void testScope(){
//singleton作用域两次输出结果一致,说明是同一个bean;
//prototype两次输出结果不一致,说明不是同一个bean
BeanScope beanScope = super.getBean("beanScope");
System.out.println(beanScope.hashCode());

BeanScope beanScope2 = super.getBean("beanScope");
System.out.println(beanScope2.hashCode());
}


三、使用注解的方式验证singleton单例在一个bean容器中只存在一份,以及实际应用举例

spring的xml文件配置自动扫描:

<context:component-scan base-package="com.jsun.test"></context:component-scan>


创建bean类,添加注解:

//注册bean
@Component("beanScope")
//设置bean的作用域范围为singleton
@Scope("singleton")
public class BeanScope {

}


单元测试加载spring容器,并运行test方法:

@Before
public void before(){
//加载配置文件,创建spring容器,应用上下文
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
context.start();
}

@After
public void after(){
context.destroy();
}

@SuppressWarnings("unchecked")
protected <T extends Object>T getBean(String beanId){
return (T)context.getBean(beanId);
}

@Test
public void testScope(){
BeanScope beanScope = super.getBean("beanScope");
System.out.println("testScope:"+beanScope.hashCode());
}

@Test
public void testScope2(){
BeanScope beanScope = super.getBean("beanScope");
System.out.println("testScope2:"+beanScope.hashCode());

}


从输出结果中,可以看出,两个test方法输出结果不一致,虽然配置bean的作用域为singleton,但是来个bean分属于不同的spring容器(每个test方法执行都会伴随加载spring容器、销毁容器),所以即使配置了bean的scope为singleton,两个bean也不是同一个bean。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring