springboot项目启动成功后执行一段代码的两种方式

1.转  springboot项目启动成功后执行一段代码的两种方式

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

3. springboot 学习之路 9 (项目启动后就执行特定方法)

4.在项目启动之后自动执行指定方法,实现同步Redis缓存数据。

  4.1 开始配置,有两种方式:ApplicationRunner和CommandLineRunner  除了可接受参数不同,其他的大同小异

  4.2 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();
    }
}

  4.3 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();
    }
}

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

测试服务MyApplicationRunner
执行MyCommandLineRunner

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

    当项目中同时实现了ApplicationRunner和CommondLineRunner接口时,可使用Order注解或实现Ordered接口来指定执行顺序,值越小越先执行

 

 

 

 

 

 

 
posted @ 2022-03-27 18:41  BBS_自律  阅读(886)  评论(0)    收藏  举报