SpringIOC容器Bean初始化和销毁回调方式
目录
- 前言
- 1.@Bean指定初始化和销毁方法
- 2.实现接口
- 3.使用jsR250
- 总结
前言
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(){ Sy编程stem.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
通过在方法上定义@PostjircCgQTLConstruct(对象初始化之后)js和@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, pythonString beanName) throws BeansException { System.out.println(beanName+"对象初始化之前"); return bean; } public Object postProcessAfterInitialization(Object bean, String beanNamwww.devze.come) 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对象初始化之后
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论