一、springboot项目启动前执行方法
ApplicationStartedEvent是Spring Boot框架中的一部分,它属于ApplicationEvents,这些事件在Spring Boot应用程序的不同生命周期阶段被发布。ApplicationStartedEvent是在Spring应用上下文开始初始化之前发布的,即在所有bean定义被注册到ApplicationContext但尚未实例化任何bean之前。
@Component
public class StartupEventListener implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
// 在这里可以访问event.getArgs()获取启动参数
// 也可以访问event.getApplicationContext()获取ApplicationContext
// 执行启动前的初始化逻辑
}
}
二、项目启动好后执行的代码
2、ApplicationReadyEvent
Spring Boot应用完全启动并准备好服务请求之后执行一些代码,你应该关注的是ApplicationReadyEvent,这个事件在所有的bean已经实例化并且所有的@PostConstruct和InitializingBean.afterPropertiesSet()方法都被调用之后发布。
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// 初始化代码
}
}
3、@PostConstruct注解
你可以在任何非静态方法上使用@PostConstruct注解,这个方法会在依赖注入完成后自动调用。但是要注意的是,@PostConstruct标记的方法不能有任何参数。
@Component
public class MyInitializer {
@PostConstruct
public void init() {
// 初始化代码
}
}
4、实现InitializingBean接口
实现Spring的InitializingBean接口,并覆盖afterPropertiesSet()方法。当Spring容器完成了bean的属性填充后,会调用此方法。
@Component
public class MyInitializer implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
// 初始化代码
}
}
5、使用CommandLineRunner或ApplicationRunner:
这两个接口允许你在Spring Boot应用启动后立即执行一些代码。CommandLineRunner接收命令行参数,而ApplicationRunner则可以访问ApplicationArguments。
@Component
public class MyInitializer implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 初始化代码
}
}
6、在配置类中使用@Bean方法:
如果初始化逻辑与某个特定的bean相关联,你可以在配置类中定义一个@Bean方法来处理初始化逻辑。
@Configuration
public class MyConfig {
@Autowired
private SomeService someService;
@Bean
public SomeOtherService someOtherService() {
SomeOtherService service = new SomeOtherService();
service.setSomeService(someService);
service.init(); // 假设SomeOtherService有一个init方法
return service;
}
}
7、监听ApplicationEvent事件:
使用Spring的事件机制,监听ApplicationReadyEvent,这个事件在Spring Boot应用完全启动后触发。
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// 初始化代码
}
}