spring bean的形式(3)

8 篇文章 0 订阅

一、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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值