欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot之ApplicationRunner/CommandLineRunner自启动

程序员文章站 2022-04-28 22:51:07
...

今天阅读Spring Boot官网时,发现其中有一段是这样:

Using the ApplicationRunner or CommandLineRunner

If you need to run some specific code once the has started, you can implement the or interfaces. Both interfaces work in the same way and offer a single method, which is called just before completes.SpringApplication``ApplicationRunner``CommandLineRunner``run``SpringApplication.run(…)

The interfaces provides access to application arguments as a string array, whereas the uses the interface discussed earlier. The following example shows a with a method:CommandLineRunner``ApplicationRunner``ApplicationArguments``CommandLineRunner``run

import org.springframework.boot.*;
import org.springframework.stereotype.*;

@Component
public class MyBean implements CommandLineRunner {

    public void run(String... args) {
        // Do something...
    }

}

If several or beans are defined that must be called in a specific order, you can additionally implement the interface or use the annotation.CommandLineRunner``ApplicationRunner``org.springframework.core.Ordered``org.springframework.core.annotation.Order

意思是spring boot应用启动后,如果需要运行某些服务,就可以实现这两个接口,相当于自启动。

今后大概率会用到,如启动时读取数据库,存入redis缓存。遂记录一下。

  • 两个接口的区别就是run方法的参数不一样,ApplicationRunner是对参数进行封装后的ApplicationArguments,CommandLineRunner是String… args。
  • 需要注意的是,在run方法中,如果方法抛出异常,会导致spring boot应用启动失败,则处理方法的时候,尽量使用try.catch处理。

这里放上Application实现样例:

/**
 * 启动时执行
 *
 * @author Source
 * @date 2020-09-08 14:17
 **/
@Component
@Order(1)
public class ApplicationRunnerImpl implements ApplicationRunner {
    private static final Logger logger = LogManager.getLogger(ApplicationRunnerImpl.class);
    
    @Override
    public void run(ApplicationArguments args) {
        logger.info("执行自启动类:" + ApplicationRunnerImpl.class);
        try {
            //do something
        } catch (Exception e) {
            logger.error("自启动程序发生异常");
        }
    }
}

可以看到,除了@Component注解之外,我这里还加了一个 @Order(1),这里Order表示自启动类的启动顺序,如果有多个类实现了ApplicationRunner接口的话,它们的执行顺序就按照@Order注解的value来,这里也可以写成@Order(value = 1),执行顺序为由小到大,1为第一个执行。

相关标签: Java Spring Boot