springboot 实现启动加载某方法
在Spring Boot中,可以使用CommandLineRunner接口或ApplicationRunner接口来实现在启动时加载某个方法。
-
使用
CommandLineRunner接口:- 创建一个类并实现
CommandLineRunner接口。 - 在实现的
run()方法中编写需要在启动时加载的逻辑。 - 例如:
import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 在启动时加载的逻辑 System.out.println("执行启动加载方法"); } } - 创建一个类并实现
-
使用
ApplicationRunner接口:- 创建一个类并实现
ApplicationRunner接口。 - 在实现的
run()方法中编写需要在启动时加载的逻辑。 - 例如:
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { // 在启动时加载的逻辑 System.out.println("执行启动加载方法"); } } - 创建一个类并实现
无论是使用CommandLineRunner还是ApplicationRunner,它们都会在Spring Boot应用启动时自动执行,并且可以通过@Component注解将其声明为一个Spring Bean
原文地址: https://www.cveoy.top/t/topic/icHa 著作权归作者所有。请勿转载和采集!