Bean的作用域及生命周期

Bean有7种作用域,只详细了解其中最常用的两种:singleton prototype

  1. singleton(单例):在每个Spring IoC容器中一个bean定义对应一个对象实例。
    singleton是spring容器的默认作用域。
<bean id="scope" class="com.woongcha.scope.scope" scope="singleton"/>
public class ScopeTest {
	public static void main(String[] args) {
		String xmlPath = "com/woongcha/scope/beans4.xml";
		//ApplicationContext在加载配置文件时,对Bean进行实例化
		ApplicationContext applicationContext =
				new ClassPathXmlApplicationContext(xmlPath);
		scope pig=new scope();
		System.out.println(applicationContext.getBean("scope"));
		System.out.println(applicationContext.getBean("scope"));
	}
}
com.woongcha.scope.Scope@3a03464
com.woongcha.scope.Scope@3a03464

两次输出结果相同,说明spring容器之创建了一个Scope类的实例。

  1. prototype(原型):在每个Spring IoC容器中一个bean定义对应多个对象实例。
<bean id="scope" class="com.woongcha.scope.scope" scope="prototype"/>
com.woongcha.scope.scope@4157f54e
com.woongcha.scope.scope@90f6bfd

两次输出结果不相同,说明spring容器之创建了两个Scope类的实例。

Bean的生命周期

  1. singleton下的Bean的生命周期完全由Spring容器管理。
  2. prototype下的Bean的生命周期Spring容器只负责创建,其他过程都有客户端代码管理。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值