栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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对象初始化之后
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/891647.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号