spring boot啓動時運行/初始化

參考:https://blog.csdn.net/u011649691/article/details/89196815
1、實現ApplicationRunner,可以進行數據庫操作,可以指定加載順序

@Component
public class DBInitializer implements ApplicationRunner {
    private Logger LOG = LoggerFactory.getLogger(DBInitializer.class);
    @Value("${thirdparty.autoTest.interval}")
    private Integer autoTestInterval;

    @Autowired
    private ServiceTypeFactory serviceTypeFactory;
    @Autowired
    private InterfaceTypeFactory interfaceTypeFactory;
    @Autowired
    private MonitorService monitorService;
    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        serviceTypeFactory.init();//serviceType初始化
        interfaceTypeFactory.init();//interfaceType初始化

        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    LOG.info("開始測試連接");
                    monitorService.testAllProject();
                    try {
                        TimeUnit.MINUTES.sleep(autoTestInterval);
                    } catch (InterruptedException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            }
        });
    }
}

2、實現CommandLineRunner ,可執行數據庫操作,可以指定加載順序

@Component  //不添加@Component則不會運行該代碼
@Order(value = 2) //指定先後加載的順序
public class StarterClass2 implements CommandLineRunner {
 
    private static final Logger logger = LoggerFactory.getLogger(StarterClass2.class);
 
    @Override
    public void run(String... args) throws Exception {
        logger.info("StarterClass2...");
    }
}

2、實現InitializingBean,此時可以做一些bean的初始化操作,不能做數據庫連接和操作
@Component
public class IntegrationInitializer implements InitializingBean {
private Logger LOG = LoggerFactory.getLogger(IntegrationInitializer.class);

    @Override
    public void afterPropertiesSet() throws Exception {
        LOG.info("test");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章