Bean的作用域

所谓Bean的作用域其实就是指Spring给我们创建出的对象的==存活范围==(存活周期)。

可以在spring配置文件中通过bean标签中的scope属性来对当前bean对象的作用域进行指定。

scope属性有五个取值:

  • ==singleton(默认)== 创建出的实例为单例模式, IOC只创建一次,然后一直存在

  • prototype 创建出的实例为多例模式, 每次获取bean的时候,IOC都给我们重新创建新对象

  • request(web) web项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.

  • session (web) web项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.

  • globalSession (用于分布式web开发) 创建的实例绑定全局session对象

applicationContext.xml

<!--
scope:指定对象的作用域
singleton:单例
prototype: 多例
-->
<bean id="account" class="com.itheima.ioc.domain.Account" scope="prototype"></bean>

测试:

/**
 * 测试bean的作用域
 */
@Test
public void testScope(){
    ApplicationContext applicationContext =
            new ClassPathXmlApplicationContext("applicationContext.xml");
    Account account1 = (Account) applicationContext.getBean("account");
    Account account2 = (Account) applicationContext.getBean("account");
    //查看多次获取的对象内存地址是否相同
    System.out.println(account1);
    System.out.println(account2);
}

观察控制台打印的对象内存地址是否相同,注意要看内存地址不要重写toString()方法

-- 单例

com.itheima.ioc.domain.Account@6a1aab78 com.itheima.ioc.domain.Account@6a1aab78

-- 多例

com.itheima.ioc.domain.Account@6a1aab78 com.itheima.ioc.domain.Account@462d5aee

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值