SpringIOC容器Bean初始化和销毁回调方式
前言
Spring Bean 的生命周期:init(初始化回调)、destory(销毁回调),在Spring中提供了四种方式来设置bean生命周期的回调:
- 1.@Bean指定初始化和销毁方法
- 2.实现接口
- 3.使用JSR250
- 4.后置处理器接口
使用场景:
在Bean初始化之后主动触发事件。如配置类的参数。
1.@Bean指定初始化和销毁方法
public class Phone {
private String name;
private int money;
//get set
public Phone() {
super();
System.out.println("实例化phone");
}
public void init(){
System.out.println("初始化方法");
}
public void destory(){
System.out.println("销毁方法");
}
}@Bean(initMethod = "init",destroyMethod = "destory")
public Phone phone(){
return new Phone();
} AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig5.class); context.close();
打印输出:
实例化phone
初始化方法
销毁方法
2.实现接口
通过让Bean实现InitializingBean(定义初始化逻辑),DisposableBean(定义销毁逻辑)接口
public class Car implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
System.out.println("对象初始化后");
}
public void destroy() throws Exception {
System.out.println("对象销毁");
}
public Car(){
System.out.println("对象初始化中");
}
}
打印输出:
对象初始化中
对象初始化后
对象销毁
3.使用JSR250
通过在方法上定义@PostConstruct(对象初始化之后)和@PreDestroy(对象销毁)注解
public class Cat{
public Cat(){
System.out.println("对象初始化");
}
@PostConstruct
public void init(){
System.out.println("对象初始化之后");
}
@PreDestroy
public void destory(){
System.out.println("对象销毁");
}
}打印输出:
对象初始化
对象初始化之后
对象销毁
4.后置处理器接口
public class Dog implements BeanPostProcessor{
public Dog(){
System.out.println("对象初始化");
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"对象初始化之前");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"对象初始化之后");
return bean;
}
}对象初始化
org.springframework.context.event.internalEventListenerProcessor对象初始化之前
org.springframework.context.event.internalEventListenerProcessor对象初始化之后
org.springframework.context.event.internalEventListenerFactory对象初始化之前
org.springframework.context.event.internalEventListenerFactory对象初始化之后
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java 中Comparable和Comparator区别比较
本文,先介绍Comparable 和Comparator两个接口,以及它们的差异;接着,通过示例,对它们的使用方法进行说明2013-09-09
SpringMVC 通过commons-fileupload实现文件上传功能
这篇文章主要介绍了SpringMVC 通过commons-fileupload实现文件上传,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-02-02


最新评论