Spring创建对象的时机

转载自

一、单例管理的对象:

  1. 默认情况下,Bean的作用域默认为单例类型。spring在读取xml文件的时候,就会创建对象。
  2. 在创建的对象的时候(先调用构造器),会去调用init-method=".."属性值中所指定的方法.
  3. 对象在被销毁的时候,会调用destroy-method="..."属性值中所指定的方法.(例如调用container.destroy()方法的时候)
  4. lazy-init="true",可以让这个对象在第一次被访问的时候创建

1.先写Bean类-LifeBean类:

public class LifeBean{
	private String name;
	private LifeBean lb;
	
	public LifeBean getLb() {
		return lb;
	}
	public void setLb(LifeBean lb) {
		this.lb = lb;
	}
	public LifeBean(){
		System.out.println("LifeBean() 构造器");
	}
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		System.out.println("setName() 方法");
		this.name = name;
	}
	
	public void init(){
		System.out.println("this is init in lifeBean");
	}
	
	public void destory(){
		System.out.println("this is destory in lifeBean");
	}
	
}

2.写配置文件life.xml:(注:配置文件时随便命名的,只要是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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <bean name="life" class="com.x.spring.bean.LifeBean"  init-method="init" destroy-method="destory"></bean>
</beans>

 

 

二,非单例管理的对象:

  1. spring读取xml文件的时候,不会创建对象.
  2. 在每一次访问这个对象的时候,spring容器都会创建这个对象,并且调用init-method=".."属性值中所指定的方法.
  3. 对象销毁的时候,spring容器不会帮我们调用任何方法。因为是非单例,这个类型的对象有很多个,spring容器一旦把这个对象交给你之后,就不再管理这个对象了。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <bean name="life" class="com.x.spring.bean.LifeBean" scope="prototype"   init-method="init" destroy-method="destory"></bean>
</beans>

 

 

由Bean的作用域即配置的Scope属性有关,默认为sinlgleton类型,随着容器初始化而实例化,全局只有一个实例

prototype类型在使用的时候实例化,每次实例化不同对象

还有request,session,global session类型

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值