SpringBoot定义容器启动任务

一、需求提出

当需要在应用容器启动的时候进行一些特定的操作,比如:读取配置文件信息,数据库连接,删除临时文件,清除缓存信息,在Spring框架下是通过ApplicationListener监听器来实现的。在SpringBoot中提供了两个接口来实现这样的需求。CommandLineRunnerApplicationRunner

二、CommandLineRunner

使用

编写配置类实现CommandLineRunner接口,重写Run方法,通过@Configuration配置到容器中

@Configuration
public class CommandLineRunnerTest implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(CommandLineRunnerTest.class);
    @Override
    public void run(String... args) throws Exception {
        logger.info("-----------------CommandLineRunner RUN SOMETHING-----------------");
    }
}

三、ApplicationRunner

使用

使用方法与CommandLineRunner相似,实现Application重写Run方法。

@Configuration
public class ApplicationRunnerTest implements ApplicationRunner {
    private Logger logger = LoggerFactory.getLogger(ApplicationRunnerTest.class);
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("-----------------ApplicationRunner RUN SOMETHING-----------------");
    }
}

四、共同点与区别

两者的功能与作用在官方文档中描述的类似,都是在应用容器启动后运行Run方法,不同点在于
ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。

五、@Order注解

当有多个ApplicationRunner实现类或CommandLineRunner实现类时,@Order可以指定执行的优先级

当Value值越小时优先级越高

经测试默认情况下ApplicationRunner的实现类优先级大于CommandLineRunner的实现类

posted @ 2021-08-30 17:58  Ho-Yu-Fung  阅读(34)  评论(0编辑  收藏  举报