首页 > 编程语言 > 详细

SpringBoot容器启动执行特定方法

时间:2021-09-01 20:25:08      阅读:15      评论:0      收藏:0      [点我收藏+]

一、需求提出

当需要在应用容器启动的时候进行一些特定的操作,比如:读取配置文件信息,数据库连接,删除临时文件,清除缓存信息,在Spring框架下是通过ApplicationListener监听器来实现的。在Spring Boot中给我们提供了两个接口来帮助我们实现这样的需求。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的实现类
技术分享图片

SpringBoot容器启动执行特定方法

原文:https://www.cnblogs.com/heyufeng0313/p/15207164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!