Spring Boot 应用启动时---如何自动运行指定代码呢?
下文笔者讲述SpringBoot启动时,运行指定代码的方法及示例分享,如下所示
SpringBoot启动时,运行指定代码的实现思路
SpringBoot启动时,运行指定代码的实现思路 1.@PostConstruct注解 2.Applicationlistener接口 3.@EventListener注解 4.ApplicationRunner接口 5.commandlinerunner接口 ============================================ @PostConstruct注解方法 (doSomething方法) 在类初始化后被调用,会首先输出。 ApplicationListener接口方法 (onApplicationEvent方法) 在应用启动后执行,会输出其相关的信息。 @EventListener注解方法 (onApplicationEvent方法) 在应用启动后执行,会输出其相关的信息。 ApplicationRunner接口方法 (run方法) 在ApplicationListener之后执行 它用于在Spring Boot应用启动后执行一些额外的逻辑。 CommandLineRunner接口方法 (run方法) 也在ApplicationListener之后执行 用于在Spring Boot应用启动后执行一些额外的逻辑。
@PostConstruct注解
@PostConstruct`注解 可标注在方法上 该方法将在类被初始化后调用 在Spring Boot应用中 你可以使用这个注解来运行一些初始化的逻辑例:
@PostConstruct public void doSomething(){ // 在应用启动后执行的代码 System.out.println("do something"); }
ApplicationListener接口
实现`ApplicationListener`接口 并监听`ApplicationStartedEvent`事件 此处逻辑将在应用启动后被触发例
import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.ApplicationListener; public class MyApplicationListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { // 在应用启动后执行的代码 System.out.println("ApplicationListener executed"); } }
@EventListener注解
使用`@EventListener`注解,可以将方法标记为事件监听器,并在特定事件发生时执行。例
import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.event.EventListener; public class MyEventListener { @EventListener(ApplicationStartedEvent.class) public void onApplicationEvent() { // 在应用启动后执行的代码 System.out.println("@EventListener executed"); } }
ApplicationRunner接口
实现`ApplicationRunner`接口 该接口`run`方法会在Spring Boot应用启动后执行。例
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { // 在应用启动后执行的代码 System.out.println("ApplicationRunner executed"); } }
CommandLineRunner接口
与`ApplicationRunner`类似,`CommandLineRunner`接口的`run`方法也在应用启动后执行。例
public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 在应用启动后执行的代码 System.out.println("CommandLineRunner executed"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。