Spring Boot之ApplicationRunner/CommandLineRunner自启动

今天阅读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为第一个执行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值