java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringIOC容器Bean初始化和销毁回调

SpringIOC容器Bean初始化和销毁回调方式

作者:terrybg

这篇文章主要介绍了SpringIOC容器Bean初始化和销毁回调方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

前言

Spring Bean 的生命周期:init(初始化回调)、destory(销毁回调),在Spring中提供了四种方式来设置bean生命周期的回调:

使用场景:

在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对象初始化之后

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文