spring2 bean作用域 和 生命周期

一 作用域
1. singleton
spring中bean的默认作用域, 每一个bean定义只有一个实例对象。默认情况下IOC容器启动时就会实例化该bean。 但我们可以指定lazy-init=“true”来延迟初始化,这时候只有第一获取该bean是才会被初始化,如:
<bean id="account" class="com.example.po.Account" lazy-init="true"/>

如果要对所有bean都延迟初始化,可以在beans上加属性,如:
<beans default-lazy-init="false" ...>



2.prototype
每次从容器中获取都是新的实例。IOC容器启动时不会被实例化,第一次获取该bean时才实例化
<bean id="account" class="com.example.po.Account"  scope="prototype"/>


3.web作用域-request


4.web作用域-session


5.web作用域-global session


二 生命周期
1. singleton bean在容器启动时被创建,容器关闭时被销毁
public class Account {
	public void init(){
		System.out.println("----initing");
	}
	public void sayHello(){
		System.out.println("----hello");
	}
	public void destroy(){
		System.out.println("----destroying");
	}
}


<bean id="account" class="com.example.po.Account"  
 init-method="init"  destroy-method="destroy"/>


@Test
public void test1(){
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("mybean.xml");
	Account account = (Account)context.getBean("account");
	account.sayHello();
	context.close();
}

输出结果:
----initing
----hello
----destroying

2. prototype bean在第一次被获取时才实例化
例如将上例改为prototype
<bean id="account" class="com.example.po.Account"  scope="prototype"
 init-method="init"  destroy-method="destroy"/>	

输出结果:
----initing
----hello

猜你喜欢

转载自oracle-api.iteye.com/blog/2067711