bean对象生命周期
在Spring中,Bean的生命周期包括Bean的定义、初始化、调用、销毁 4个阶段
bean初始化 方式一
- 在bean标签配置 init-method属性 来指定初始化时调用的方法
public class TypeDao {
public void test1() {
System.out.println("TypeDao...");
}
}
<bean id="typeDao" class="com.zh.dao.TypeDao" scope="singleton" init-method="test1" lazy-init="true"/>
bean初始化 方式二
- 实现 import org.springframework.beans.factory.InitializingBean 接口
public class TypeDao implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("实现 InitializingBean 初始化Bean ,重写afterPropertiesSet方法,初始化Bean");
}
}
bean调用
- BeanFactory 或 ApplicationContext
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring04.xml");
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring04.xml");
- ApplicationContext 接口间接继承 BeanFactory
bean销毁
- bean标签添加 destroy-method 属性,指定销毁方法
<bean id="typeDao" class="com.zh.dao.TypeDao" destroy-method="destroy"/>
- 通过 AbstractApplicationContext 接口,close方法销毁bean对象
AbstractApplicationContext aac = new ClassPathXmlApplicationContext("spring04.xml");
aac.close();