配置Spring管理的bean的作用域

Spring管理的bean的作用域有:

1.singleton 

在每个Spring IoC容器中,一个bean定义只有一个对象实例。 
以Spring的三种实例化Bean的方式的案例为基础,我们举例说明。首先我们将Spring的配置文件——beans.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="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>

</beans>

然后再将SpringTest类的代码改为:

public class SpringTest {

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器
        PersonService personService1 = (PersonService) ctx.getBean("personService"); // 从Spring容器取得bean
        PersonService personService2 = (PersonService) ctx.getBean("personService"); 
        System.out.println(personService1 == personService2); // 输出true,两个变量所引用的对象是同一个,证实了默认情况下这个bean交给Spring容器管理之后,这个bean是一个单实例。
    }

}

最后,测试test()方法,Eclipse的控制台输出true,说明了默认情况下bean交给Spring容器管理之后,这个bean就是一个单实例(单例模式)的,即每次调用getBean()方法,获取到的都是同一个bean实例。

2.prototype 

现在我们有了一个新的需求,那就是在客户端每次调用getBean()方法,获取到的都是一个新的bean实例,这个时候就需要用到prototype作用域了。每次从容器获取bean都是新的对象。
为了证明这一点,我们只须将Spring的配置文件——beans.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="personService" class="cn.itcast.service.impl.PersonServiceBean" scope="prototype"></bean>

</beans>

SpringTest类的代码不用改动,此时测试test()方法,Eclipse的控制台会输出false。这就已经证实了若bean的作用域置为prototype,那么每次从Spring容器获取bean都将是新的对象。

其次,还有一些不太常用的的,包括

  • request
  • session
  • global session

转载于:https://www.cnblogs.com/zbdouble/p/9227687.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值