SpringBoot项目启动后自动执行指定方法

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

  • ApplicationRunner

    package org.config;
    
    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值决定,值小先执行
     * 
     * @author single-聪
     * @date 2019年10月31日
     * @version 0.0.1
     */
    @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

    package org.config;
    
    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值决定,值小先执行
     * 
     * @author single-聪
     * @date 2019年10月31日
     * @version 0.0.1
     */
    @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();
    	}
    }
    

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

测试服务MyApplicationRunner
执行MyCommandLineRunner

更换@Order注解的value值可以自定义执行顺序(某些操作需要有先后顺序)

发布了43 篇原创文章 · 获赞 25 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/single_cong/article/details/102847821