如何在Spring初始化Bean或销毁Bean前执行某些操作

阅读文本大概需要3分钟。

0x01:通过在Bean中定义init-method 和 destory-method方法

  1. public class Car {

  2. public Car() {

  3. System.out.println("Car's Constructor..");

  4. }

  5. public void init(){

  6. System.out.println("Car's Init...");

  7. }

  8. public void destory(){

  9. System.out.println("Car's Destroy...");

  10. }

  11. }

  1. @Bean(initMethod = "init",destroyMethod = "destory")

  2. public Car car(){

  3. return new Car();

  4. }

0x02: 通过@PostConstruct和@PreDestroy方法实现初始化和销毁bean之前进行的操作

  1. import javax.annotation.PostConstruct;

  2. import javax.annotation.PreDestroy;

  3. @Service

  4. public class CustomerService

  5. {

  6. String message;

  7. public String getMessage() {

  8. return message;

  9. }

  10. public void setMessage(String message) {

  11. this.message = message;

  12. }

  13. @PostConstruct

  14. public void initIt() throws Exception {

  15. System.out.println("Init method after properties are set : " + message);

  16. }

  17. @PreDestroy

  18. public void cleanUp() throws Exception {

  19. System.out.println("Spring Container is destroy! Customer clean up");

  20. }

  21. }

这两个注解是JDK自带的,因此与Spring的耦合性较低(必须要Spring扫描到这个java类才能执行使用该注解的方法)

0x03: 通过bean实现InitializingBean和DisposableBean接口

  1. @Service

  2. public class CustomeService implements InitializingBean, DisposableBean

  3. {

  4. String message;

  5. public String getMessage() {

  6. return message;

  7. }

  8. public void setMessage(String message) {

  9. this.message = message;

  10. }

  11. public void afterPropertiesSet() throws Exception {

  12. System.out.println("Init method after properties are set : " + message);

  13. }

  14. public void destroy() throws Exception {

  15. System.out.println("Spring Container is destroy! Customer clean up");

  16. }

  17. }

往期精彩

01 漫谈发版哪些事,好课程推荐

02 Linux的常用最危险的命令

03 精讲Spring Boot—入门+进阶+实例

04 优秀的Java程序员必须了解的GC哪些

05 互联网支付系统整体架构详解

关注我

每天进步一点点

喜欢!在看☟

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG弄潮儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值