简易过程
1.Bean实例化——调用无参构造器
2.Bean属性设值——调用Setter赋值
3.Bean初始化——调用init-method()
4.Bean使用
5.Bean销毁——调用destory-method()
完整过程
1.Bean实例化
2.Setter设值
3.setBeanName(),传入Bean当前的id值
4.setFactory(),传入当前 Factory 实例的引用
5.setApplicationContext(),传入当前 ApplicationContext 实例的引用
6.postProcessBeforeInitialzation() 后处理器在init-method()之前的操作
7.afterPropertiesSet()
8.init-method()完成初始化
9.postProcessAfterInitialization() 后处理在init-method()方法之后的操作
10.判断Bean的作用域
singleton放入loc容器的缓存池中,触发Spring对Bean的管理
prototype交给调用者管理
11.destory-method()销毁
Bean类代码如下
/**
* 生命周期
* 通过XML配置,实现初始化回调和销毁回调
*/
public class MyBean {
//无参构造器
public MyBean() {
System.out.println("step1 执行无参构造创建bean实例");
}
private String name;
//setter方法
public void setName(String name) {
this.name = name;
System.out.println("step2 调用set方法完成属性设值");
}
//执行初始化方法
public void initMehtod(){
System.out.println("step3 执行初始化方法");
}
//执行销毁方法
public void destroyMehtod(){
System.out.println("step5 执行销毁方法");
}
@Override
public String toString() {
return "MyBean{" +
"name='" + name + '\'' +
'}';
}
}
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean生命周期 -->
<!--通过XML配置-->
<bean id="myBean" class="org.example.lifecycle.MyBean" init-method="initMehtod" destroy-method="destroyMehtod">
<property name="name" value="zevin"/>
</bean>
</beans>
测试类
public class Test{
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/Beans.xml");
MyBean myBean = (MyBean) context.getBean("myBean");
System.out.println("step4 获取创建bean实例对象");
System.out.println(myBean);
//手动销毁Bean
((ClassPathXmlApplicationContext)context).close();
}
}
结果如下
step1 执行无参构造创建bean实例
step2 调用set方法完成属性设值
step3 执行初始化方法step4 获取创建bean实例对象
step5 执行销毁方法