配置Spring管理的bean的作用域

本文介绍了Spring框架中Bean的两种作用域:singleton和prototype。通过示例代码演示了如何使用JUnit测试来验证这两种作用域的区别。

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" scope="singleton" ></bean>

这里的scope值有2种,singleton和prototype。singleton是单例模式,意思是每次实例化的bean不变都相同;而prototype

是多列模式,每次实例化后的bean都不相同。

在junit测试类中可以这样进行判断:

@Test
public void instanceSpring(){
AbstractXmlApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
PersonServiceBean ps=(PersonServiceBean) ctx.getBean("personService");
PersonServiceBean ps2=(PersonServiceBean) ctx.getBean("personService");
System.out.println(ps==ps2 );
}

如果返回值为true则说明scope=“singleton”,反之则scope="prototype"。默认时是singleton状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值