bean生命周期
(1)从对象创建到对象销毁的过程
2、bean的生命周期大体上可分五个阶段、如果加上后置处理器可分为7个阶段。
(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(2.5)、postProcessBeforeInitialization:初始化之前(后置处理器)
(3)调用 bean 的初始化的方法(需要进行配置初始化的方法)
(3.5)、postProcessAfterInitialization:初始化之后(后置处理器)
(4)bean 可以使用了(对象获取到了)
(5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)
package com.itheima.pojo;
/**
* @version 1.0
* @Author kevin
* @create 2022/7/14
* 该类演示 bean 生命周期的7个过程。
*/
public class Order1 {
private String name;
public Order1() {
System.out.println("第一步,初始化构造器");
}
public void setName(String name) {
System.out.println("第二步,为bean属性注入值");
this.name = name;
}
public void initMethod(){
System.out.println("第三步,执行初始化 函数(需要在配置文件配置)");
}
public void destroyMethod(){
System.out.println("第五步,执行销毁 函数(需要在配置文件配置)");
}
}
<?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">
<!--改xml文件配置演示bean的生命周期-->
<!-- 值得注意的是,当配置了后置处理器之后,
改文件中的所以bean的初始化前后都会 执行后置处理器的两个函数-->
<!-- 配置后置处理器-->
<bean id="myBean" class="com.itheima.pojo.MyBean"></bean>
<bean id="order1" class="com.itheima.pojo.Order1" init-method="initMethod"
destroy-method="destroyMethod">
<property name="name" value="Miller"></property>
</bean>
</beans>
import com.itheima.pojo.Order;
import com.itheima.pojo.Order1;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @version 1.0
* @Author kevin
* @create 2022/7/13
*/
public class TestDemo2 {
//该方法测试 bean 生命周期的7个过程
@Test
public void test2(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
Order1 order = (Order1) context.getBean("order1");
System.out.println("第四步,获得bean的初始化对象");
System.out.println(order);
//手动让bean实例销毁
//((ClassPathXmlApplicationContext)context).close();
context.close();
}
}
IOC 操作 Bean 管理(xml 自动装配) 略。。。
IOC 操作 Bean 管理(外部属性文件) 略。。。