如何在Spring Bean创建销毁前执行自定义行为

Bean创建后和Bean销毁前执行自定义行为的三种方式。

一、实现 InitializingBean 和 DisposableBean 接口

InitializingBeanBean创建完成后调用;DisposableBeanBean销毁前调用

1
2
3
4
5
6
7
8
9
10
11
12
public class Hello implements InitializingBean, DisposableBean {

@Override
public void destroy() throws Exception {
System.out.println("destroy bean");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("bean init");
}
}

二、使用 JSR-250 的 @PostConstruct 和 @PreDestroy 注解

PostConstructBean创建完成后调用;PreDestroyBean销毁前调用

1
2
3
4
5
6
7
8
9
@PostConstruct
public void init() {
System.out.println("====== bean init ======");
}

@PreDestroy
public void beforeDestroy() {

}

三、在<bean/> 或 @Bean 里配置初始化和销毁方法

1
@Bean(name = "hello", initMethod = "init", destroyMethod = "destroy")

如何在Spring Bean创建销毁前执行自定义行为
https://probiecoder.cn/spring/bean.html
作者
duwei
发布于
2024年5月8日
许可协议