Spring 2.5 Bean 的生命周期
初始化
init-method="指定bean类定义的初始方法"
销毁
destroy-method="指定bean类定义的销毁方法"
bean的实例构造:
bean的实例化如果<bean scope="singleton"/>是默认单例,那么会在Spring容器启动时就实例化,
如果scope非单例,那么会在调用这个bean时才初化,如果想要 scope="singleton"时,调用时再实例化,可以配置延迟实例化属性 lazy-init="true" false 则不延迟实例,
------------------------------------------------------
代码样例:
初始化
init-method="指定bean类定义的初始方法"
销毁
destroy-method="指定bean类定义的销毁方法"
bean的实例构造:
bean的实例化如果<bean scope="singleton"/>是默认单例,那么会在Spring容器启动时就实例化,
如果scope非单例,那么会在调用这个bean时才初化,如果想要 scope="singleton"时,调用时再实例化,可以配置延迟实例化属性 lazy-init="true" false 则不延迟实例,
------------------------------------------------------
代码样例:
package test.service;
public interface PersonService {
public void save();
}
package test.service.impl;
import test.service.PersonService;
public class PersonServiceBean implements PersonService {
public PersonServiceBean(){
System.out.println("构造");
}
public void init(){
System.out.println(this.getClass().getName() + " 我被初始化了");
}
public void save(){
System.out.println("sava function");
}
public void destroy(){
System.out.println(this.getClass().getName() + " 我被销毁了");
}
}
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.service.PersonService;
//测试类
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception{
}
@Test public void instanceSpring(){
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService p = (PersonService) ctx.getBean("personService");//get bean
p.save();//调用方法
ctx.close();//关闭spring容器,这里测试destroy属性
}
}
//配置文件
<?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.0.xsd"
>
<bean id="personService" class="test.service.impl.PersonServiceBean" scope="singleton" lazy-init="true" init-method="init" destroy-method="destroy"></bean>
</beans>
// scope="singleton" bean为单例,这里设置scope默认就是单例
// lazy-init="true" 表明在getBean时才实例化这个bean
// init-method="init" 调用init()方法初始化这个bean 此方法是自定义也可以是其他已有的
// destroy-method="destroy" 调用定义的destroy方法来销毁bean,须调用AbstractApplicationContext下面的close方法,才会执行,