本文主要是介绍SpringIOC容器Bean初始化和销毁回调方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《SpringIOC容器Bean初始化和销毁回调方式》:本文主要介绍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(){ 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.chinasem.cne) 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对象初始化之后
总结
这篇关于SpringIOC容器Bean初始化和销毁回调方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!