zoukankan      html  css  js  c++  java
  • SpringBoot项目启动后执行某个方法的方式(开机启动)

    springboot项目启动自动触发方法场景:

    做这个的原因:前端数据一直在变化,导致我每次打包之后需要清缓存处理缓存数据,故而有了本文,在项目启动之后自动执行指定方法,本文作用是实现同步缓存数据。
    开始配置,有两种方式:ApplicationRunner和CommandLineRunner

    实现ApplicationRunner接口

    import org.service.PushMessageService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * 实现ApplicationRunner接口,执行顺序按照value值决定,值小先执行
     */
    @Slf4j
    @Component
    @Order(value = 1)
    public class MyApplicationRunner implements ApplicationRunner {
    	@Autowired
    	private PushMessageService pushMessageService;
    
    	@Override
    	public void run(ApplicationArguments args) throws Exception {
    		log.info("测试服务MyApplicationRunner");
    		pushMessageService.resetRedis();
    	}
    }

    实现CommandLineRunner接口

    import org.service.PushMessageService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * 实现MyCommandLineRunner接口,执行顺序按照value值决定,值小先执行
     */
    @Slf4j
    @Component
    @Order(value = 2)
    public class MyCommandLineRunner implements CommandLineRunner {
    	@Autowired
    	private PushMessageService pushMessageService;
    
    	@Override
    	public void run(String... args) throws Exception {
    		log.info("执行MyCommandLineRunner");
    		// 同步缓存中的通知消息数目
    		pushMessageService.resetRedis();
    	}
    }
    

    @Component注解相应的类,并重写run方法,若存在多个启动执行的任务,可利用在类上使用@Order注解来指定顺序。

    在上述两个类中PushMessageService 为自己的service接口,具体是什么随意,使用方式和controller使用一样,这样项目启动之后日志打印顺序为:

    测试服务MyApplicationRunner
    执行MyCommandLineRunner
    我话讲完!谁赞成?谁反对?
  • 相关阅读:
    使用Doxygen生成net帮助文档
    Mac OSX 下配置 LNMP开发环境
    vue相关网站资源收集
    AJAX 相关笔记
    toLocaleDateString()
    前端关于图片的优化
    css 水平垂直居中的方法总结
    Mac下安装Twig模版引擎的方法
    gulp基础使用总结
    js中元素操作的有关内容与对比
  • 原文地址:https://www.cnblogs.com/wffzk/p/15747687.html
Copyright © 2011-2022 走看看