Spring创建Bean完成后执行指定代码的几种实现方式
Spring中Bean创建完成后执行指定代码的几种实现方式
在实际开发中经常会遇到在spring容器加载完某个bean之后,需要执行一些业务代码的场景。比如初始化配置、缓存等。有以下几种方式可以实现此需求
1、 实现ApplicationListener接口
实现ApplicationListener接口并实现方法onApplicationEvent()方法,Bean在创建完成后会执行onApplicationEvent方法
@Component
public class DoByApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
public DoByApplicationListener() {
System.out.println("DoByApplicationListener constructor");
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
System.out.println("DoByApplicationListener do something");
}
}
}2、 实现InitializingBean接口
实现InitializingBean接口并实现方法afterPropertiesSet(),Bean在创建完成后会执行afterPropertiesSet()方法
@Component
public class DoByInitializingBean implements InitializingBean {
public DoByInitializingBean() {
System.out.println("DoByInitializingBean constructor");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitByInitializingBean do something");
}
}3、 使用@PostConstruct注解
在Bean的某个方法上使用@PostConstruct注解,Bean在创建完成后会执行该方法
@Component
public class DoByPostConstructAnnotation {
public DoByPostConstructAnnotation() {
System.out.println("DoByPostConstructAnnotation constructor");
}
@PostConstruct
public void init(){
System.out.println("InitByPostConstructAnnotation do something");
}
}转载自:https://segmentfault.com/a/1190000019622443?utm_source=tag-newest
到此这篇关于Spring中Bean创建完成后执行指定代码的几种实现方式的文章就介绍到这了,更多相关Spring Bean创建完成后执行指定代码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
使用Shell脚本实现SpringBoot项目自动化部署到Docker的操作指南
在日常项目开发中,我们经常会将SpringBoot项目打包并部署到服务器上的Docker环境中,为了提升效率、减少重复操作,我们可以通过Shell脚本实现自动化部署,所以本文给大家介绍了使用Shell脚本实现SpringBoot项目自动化部署到Docker的操作指南,需要的朋友可以参考下2025-05-05
Liquibase结合SpringBoot使用实现数据库管理功能
Liquibase 是一个强大的数据库管理工具,它帮助你通过自动化管理数据库的变更、版本控制、和回滚,简化了开发中的数据库迁移工作,这篇文章主要介绍了Liquibase结合SpringBoot使用实现数据库管理,需要的朋友可以参考下2024-12-12
SpringBoot基于RabbitMQ实现消息可靠性的方法
RabbitMQ 提供了 publisher confirm 机制来避免消息发送到 MQ 过程中丢失,这种机制必须给每个消息指定一个唯一ID,消息发送到MQ以后,会返回一个结果给发送者,表示消息是否处理成功,本文给大家介绍了SpringBoot基于RabbitMQ实现消息可靠性的方法,需要的朋友可以参考下2024-04-04


最新评论