SpringBoot2.1.x在启动后调用一次的4种方法,可以用于定时任务触发、数据初始化、初始化系统参数、文件初始化。

最近在做的一个SpringBoot项目需要工程启动后,查询数据库定时任务表配置信息,触发定时任务,查了一下SpringBoot2.X可以实现的一些方法,可根据不同使用场景使用,具体如下:

1、实现CommandLineRunner接口

2、实现ApplicationRunner接口

3、实现ApplicationListener接口

4、使用@PostConstruct 注解

5、实现InitializingBean接口

CommandLineRunner、ApplicationRunner 接口是在容器启动成功后的最后一步回调(类似开机自启动)。

区别在于接收的参数不一样。CommandLineRunner的参数是最原始的参数,没有做任何处理。ApplicationRunner的参数是ApplicationArguments,是对原始参数做了进一步的封装。

ApplicationArguments是对参数(main方法)做了进一步的处理,可以解析--name=value的,我们就可以通过name来获取value(而CommandLineRunner只是获取--name=value)

使用 @PostConstruct 注解同样可以帮助我们完成资源的初始化操作,前提是这些初始化操作不需要依赖于其它Spring beans的初始化工作。

InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

import com.auto.trade.entities.SpringCorn;
import com.auto.trade.market.config.ScheduleConfig;
import com.auto.trade.services.SpringCornService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 在项目启动过程中,完成定时任务的初始化
 * @QC班长
 * @date 20190127
 */
@Component
public class TradeInitializingBean implements InitializingBean{

    @Autowired
    private SpringCornService springCornService;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("=================>>>TradeApplicationRunner...init resources by implements InitializingBean");
        List<SpringCorn> cornList= springCornService.getAll();
        ScheduleConfig scheduleConfig=new ScheduleConfig();
        scheduleConfig.startCron(cornList);
    }

}
发布了302 篇原创文章 · 获赞 250 · 访问量 172万+

猜你喜欢

转载自blog.csdn.net/qq_35624642/article/details/86676333