springboot集成flyway,及启动后初始化问题解决ApplicationListener,CommandLineRunner

1、配置pom.xml

        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
            <version>6.0.8</version>
        </dependency>

注意:版本自行修改
spring-boot-autoconfigure-2.2.6.RELEASE.jar对应flyway版本6.0.8

2、spring配置

# Spring配置
spring:
  flyway:
    baseline-on-migrate: false
    locations: classpath:/db/migration

3、项目启动之后,需要一些初始化的操作,有些项目中有@PostConstruct,会在flyway之前先运行,涉及到数据库的操作就会出问题,下面有2种解决办法,解决这个问题。他们都会在系统启动之后,运行一次。

1、放到ApplicationListener里运行

@Slf4j
@Component
public class InitConfig implements ApplicationListener<ApplicationStartedEvent> {
    
    @Autowired
    private ISysJobService sysJobService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 项目启动时,初始化参数
     */
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info("===> init param");
        sysConfigService.init();
        log.info("===> init dict");
        sysDictTypeService.init();
        try {
            log.info("===> init job");
            sysJobService.init();
        } catch (Exception e) {
            log.error("{}", e.getMessage(), e);
        }
    }
}

2、放到CommandLineRunner里面运行


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ApplicationStartupRunner implements CommandLineRunner {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void run(String... args) throws Exception {
        log.info("ApplicationStartupRunner run method Started !!");
        try {
            log.info("[CommandLineRunner]===> init initSipRule");
            redisUtils.initSipRule();
        } catch (Exception e) {
            log.error("ApplicationStartupRunner error. {}", e.getMessage(), e);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容