Execute a piece of other logic immediately after the Spring Boot application starts

Some simple requirements need to execute or print some data immediately after the project starts. You can use Spring Boot's ApplicationRunner or CommandLineRunner interface to execute a piece of logic immediately after the application starts. These two interfaces are used to define the tasks to be executed after the Spring Boot application is started.

  1. Use the ApplicationRunner interface:
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. Use the CommandLineRunner interface:
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("应用启动后立即执行");
    }
}

Whether you use ApplicationRunner or CommandLineRunner, you only need to implement the corresponding interface and write the logic code to be executed in the run method. In this way, after the Spring Boot application is started, the task will be automatically called and executed.

おすすめ

転載: blog.csdn.net/weixin_39709134/article/details/132068219