Spring对象的作用域

*  在配置文件中,scope

                  "singleton" 

                     *  默认值

                     *  spring产生的bean只有一个实例

                     *  处于单例模式的bean的创建、初始化、销毁都是受spring容器管理的

                     *  在容器关闭的时候执行销毁工作

                  "prototype"

                     *  多例

                     *  spring容器负责该bean的创建、初始化,但是销毁工作程序员做

                     *  无论该bean的lazy-init为什么值,都在context.getBean时创建对象

                     *  如果该bean中有资源对象,手动关闭

<?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-2.5.xsd">
       
       <!-- 
         scope决定bean的范围
          singleton  单例   默认
          prototype  原型   多例
       -->
         <bean id="helloWorld" class="cn.itcast.spring01.scope.HelloWorld" scope="prototype"></bean>
</beans>


 

public class ScopeTest {
	/**
	 * 由spring容器产生的bean默认是单例模式
	 *    在spring的配置文件中:
	 *   	 scope:
	 *          singleton  默认的形式
	 *    如果写默认的形式,一个集合或者一个数据出现在了类的属性中,这个数据将成为全局的数据(共享数据),应该
	 *    注意并发问题
	 *  当spring容器中的bean是多例,则不管配置文件中的lazy-init为default、false还是true,在
	 *     context.getBean时才要为bean创建对象
	 */
	@Test
	public void test(){
		ApplicationContext context = new ClassPathXmlApplicationContext("cn/itcast/spring0401/scope/applicationContext.xml");
		
		HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");
		helloWorld.s.add("aaa");
		helloWorld.s.add("bb");
		HelloWorld helloWorld1 = (HelloWorld)context.getBean("helloWorld");
		helloWorld1.s.add("cc");
		System.out.println(helloWorld.s.size());
	}
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

招风的黑耳

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

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

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

打赏作者

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

抵扣说明:

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

余额充值