配置Spring管理的bean的作用域

Spring管理的bean的作用域有:

  • 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实例。

  • 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李阿昀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值