Spring注解驱动开发 第九节 使用@PostConstruct与@PreDestroy自定义初始化与销毁方法

本文介绍在Spring框架中如何使用@PostConstruct与@PreDestroy注解自定义bean的初始化与销毁方法,通过示例代码展示Dog类的生命周期,包括构造器加载、初始化及容器关闭前的销毁过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring注解驱动开发 第九节 使用@PostConstruct与@PreDestroy自定义初始化与销毁方法

上一节,我们采用实现InitializingBean与DisposableBean接口来自定义初始化与销毁方法,现在我们使用第三种方式自定义。

@Component
public class Dog {
    public Dog(){
        System.out.println("Dog 默认构造器加载了...");
    }
    @PostConstruct
    public void init(){
        System.out.println("Dog @PostConstruct ...");
    }
    @PreDestroy
    public void destory(){
        System.out.println("Dog destory ...");
    }
}

@PostConstruct注解表示bean被创建,属性被赋值后进行调用初始化操作。@PreDestroy注释表示spring容器关闭前对bean的逻辑操作。
打印结果:

四月 23, 2019 2:54:06 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 14:54:06 GMT+08:00 2019]; root of context hierarchy
black构造器被调用了....
black afterPropertiesSet ...
Dog 默认构造器加载了...
Dog @PostConstruct ...
Blue被加载到spring容器中了...
Blue init...
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig4
black
dog
blue
Blue destory...
Dog destory ...
black destroy ...
四月 23, 2019 2:54:07 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 14:54:06 GMT+08:00 2019]; root of context hierarchy

Process finished with exit code 0

可以看到Dog首先被spring调用构造器创建对象,然后spring调用了我们自定义的初始化方法,当容器销毁前,调用我们自定义的销毁方法。这里需要注意这种方法同时也是JSR250规范

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值