最近在做一个项目, 需要Tomcat启动后就执行一段代码

在这里需要用到CommandLineRunner这个接口, Spring boot的CommandLineRunner接口主要用于实现在应用初始化后,去执行一段代码块逻辑,这段初始化代码在整个应用生命周期内只会执行一次, 下面是具体办法

创建一个ApplicationStartupRunner类继承CommandLineRunner接口, 在类上加@Component

如果你有多个CommandLineRunner的实现类可以使用@Order(value=1)注解进行排序, 制定他们的执行循序

@Component
@Order(value=1) // 当存在多个CommandLineRunner的实现类使用此注解定义执行顺序, 数值越小越先执行
public class ApplicationStartupRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("你要执行的代码!"); } }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-26
  • 2021-10-08
  • 2022-12-23
  • 2022-02-28
  • 2021-06-12
猜你喜欢
  • 2021-08-18
  • 2022-12-23
  • 2021-08-25
  • 2021-11-29
  • 2022-01-05
  • 2021-10-04
  • 2022-12-23
相关资源
相似解决方案