一、含义:bean从创建到销毁的过程。
二、bean的生命周期
(1)利用构造函数创建bean。
(2)利用set方法给bean注入属性。
(3)如果创建了前置处理器,则调用postProcessBeforeInitialization方法。
(4)调用bean的初始化方法。
(5)如果创建了后置处理器,则调用postProcessAfterInitialization方法。
(6)bean创建成功。
(7)当容器关闭时,调用bean的销毁方法。
三、具体实现
(1)创建类
User类
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("利用set方法给bean注入属性");
}
public User() {
System.out.println("利用构造函数创建bean");
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public void initMethod(){
System.out.println("调用bean的初始化方法");
}
public void destoryMethod(){
System.out.println("调用bean的销毁方法");
}
}
后置处理器类MyBeanPostProcessor
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化前执行前置处理器中的postProcessBeforeInitialization方法");
return null;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化后执行后置处理器中的postProcessAfterInitialization方法");
return null;
}
}
(2)编写配置文件spring-config.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="user" class="com.wsh.pojo.User" init-method="initMethod" destroy-method="destoryMethod">
<property name="name" value="张三"></property>
</bean>
<bean id="myBeanPostProcessor" class="com.wsh.pojo.MyBeanPostProcessor">
</bean>
</beans>
(3)JAVA程序
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
User user = context.getBean("user", User.class);
((ClassPathXmlApplicationContext)context).close();
}
输出
利用构造函数创建bean
利用set方法给bean注入属性
初始化前执行前置处理器中的postProcessBeforeInitialization方法
调用bean的初始化方法
初始化后执行后置处理器中的postProcessAfterInitialization方法
调用bean的销毁方法