9.Bean容器的生命周期(重要)
beanLife类
package Spring5.beanLife;
public class beanLife {
private String name;
private String surname;
public beanLife(){
System.out.println("调用无参构造方法创建bean实例");
}
public beanLife(String name,String surname){
this.name=name;
this.surname=surname;
}
public void setName(String name) {
System.out.println("调用setName方法给属性注入值");
this.name = name;
}
public String getName() {
return name;
}
public void setSurname(String surname) {
System.out.println("调用setSurname方法给属性注入值");
this.surname = surname;
}
public String getSurname() {
return surname;
}
public void init(){
System.out.println("给bean实例初始化");
}
public void destroy(){
System.out.println("销毁bean容器");
}
}
myBeanPostProcessor类
package Spring5.beanLife;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class myBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化前调用处理器方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化后调用处理器方法");
return bean;
}
}
bean8.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beanLife" class="Spring5.beanLife.beanLife" init-method="init" destroy-method="destroy">
<property name="name" value="张磊"></property>
<property name="surname" value="帅哥"></property>
</bean>
<!--配置后置处理器-->
<bean id="myBeanPostProcessor" class="Spring5.beanLife.myBeanPostProcessor"></bean>
</beans>
Test类
public class TEST {
/*
bean的生命周期(非常重要):从对象的创建到销毁
1.通过构造器创建bean实例(无参构造)
2.为bean的属性设置值以及对其他bean的引用
调用后置处理器中的一个方法
3.调用bean的初始化方法(需要进行配置初始化的方法)
调用后置处理器中的另一个方法
4.bean可以使用了(对象可以获取到)
5.容器关闭时,调用bean的销毁方法(需要配置销毁方法)
*/
@Test
public void testBean8(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean8.xml");
beanLife b = context.getBean("beanLife", beanLife.class);
//手动关闭bean容器
((ClassPathXmlApplicationContext)context).close();
}
}
测试结果
调用无参构造方法创建bean实例
调用setName方法给属性注入值
调用setSurname方法给属性注入值
初始化前调用处理器方法
给bean实例初始化
初始化后调用处理器方法
销毁bean容器