Spring IOC 容器可以管理 Bean 的生命周期, Spring 允许在 Bean 生命周期的特定点执行定制的任务. Spring IOC 容器对 Bean 的生命周期进行管理的过程: 通过构造器或工厂方法创建 Bean 实例 为 Bean 的属性设置值和对其他 Bean 的引用 调用 Bean 的初始化方法 Bean 可以使用了 当容器关闭时, 调用 Bean 的销毁方法
在 Bean 的声明里设置 init-method 和 destroy-method 属性, 为 Bean 指定初始化和销毁方法.
附上个人demo
< span style = "font-size:24px;" > < bean id = "student" class = "Spring19.Student" init-method = "init" destroy-method = "destory" > < property name = "name" value = "Sam" > </ property > </ bean > </ span >
package Spring19; public class Student { private String name; public String getName() { return name; } public void setName(String name) { this.name = name ; } @Override public String toString() { return "Student [name = " + name + " ]"; } public void init(){ System.out.println("Student init..."); } public void destory(){ System.out.println("Student destory..."); } public Student() { System.out.println("Student construtor...."); } public Student(String name) { super(); this.name = name ; System.out.println("Student construtor...."); } }
Spring IOC 容器对 Bean 的生命周期进行管理的过程: 通过构造器或工厂方法创建 Bean 实例 为 Bean 的属性设置值和对其他 Bean 的引用 将 Bean 实例传递给 Bean 后置处理器的 postProcessBeforeInitialization 方法 调用 Bean 的初始化方法 将 Bean 实例传递给 Bean 后置处理器的 postProcessAfterInitialization方法 Bean 可以使用了 当容器关闭时, 调用 Bean 的销毁方法
以下附上接口实现
package Spring19; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class testBeanPostProcess implements BeanPostProcessor { public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException { System.out.println("postProcessAfterInitialization..and bean is "+arg0+ " bean name is "+ arg1 ); return arg0; } public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException { System.out.println("postProcessBeforeInitialization..and bean is "+arg0+ " bean name is "+ arg1 ); return arg0; } }< strong style = "color: rgb(0, 0, 153);" > </ strong >
<strong><span style="font-size:32px;color:#ff0000;"><bean class="Spring19.testBeanPostProcess"></bean></span></strong>
运行结果:
Student construtor.... postProcessBeforeInitialization..and bean is Student [name=Sam] bean name is student Student init... postProcessAfterInitialization..and bean is Student [name=Sam] bean name is student Student [name=Sam] Student destory...