Spring Boot应用启动之后立刻执行一段其他逻辑

有些简单需求需要在项目启动之后马上执行或打印一些数据,可以使用Spring Boot的ApplicationRunner或CommandLineRunner接口来在应用启动之后立即执行一段逻辑。这两个接口都是用来定义在Spring Boot应用启动完成后要执行的任务。

  1. 使用ApplicationRunner接口:
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("应用启动后立即执行");
    }
}
  1. 使用CommandLineRunner接口:
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还是CommandLineRunner,只需要实现对应的接口,并在run方法中编写需要执行的逻辑代码即可。这样,在Spring Boot应用启动完成后,该任务就会被自动调用并执行。

猜你喜欢

转载自blog.csdn.net/weixin_39709134/article/details/132068219
今日推荐