平时项目里可能会遇到,在启动项目的时候,需要进行初始化操作,如执行一段SQL脚本,或者将查询数据写入本地或者是缓存服务器,或者把某些热点数据加载到Redis中去等等。这时候可以使用下面的几种方式来实现。

测试:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName: ExecutionOrderTest
 * @Description: 执行顺序和优先级测试
 * @author: xiaofei
 */
@Component
public class ExecutionOrderTest implements ApplicationRunner, CommandLineRunner {

    @Autowired
    private TestService testService;

    public ExecutionOrderTest() {
        System.out.println("ExecutionOrderTest构造函数执行......");
    }

    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct开始执行......");
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("实现ApplicationRunner........");
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("实现CommandLineRunner........");
    }
}
@Component
class TestService {
    public TestService() {
        System.out.println("TestService开始执行......");
    }
}

执行结果:

ExecutionOrderTest构造函数执行......
TestService开始执行......
@PostConstruct开始执行......
实现ApplicationRunner........
实现CommandLineRunner........

Constructor(构造方法) —> @Autowired(依赖注入) —> @PostConstruct(注释的方法) —> ApplicationRunner —> CommandLineRunner

/**
* 项目启动时,初始化参数到缓存
*/
@PostConstruct
public void init() {
    LOGGER.info("初始化系统参数到Redis中...");
    List<Config> configsList = configMapper.selectConfigList(new Config());
    for (Config config : configsList) {
        redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
    }
}

一般用于初始化一些系统参数到缓存中去,因为系统参数不是经常修改的,可以在项目启动时存放进去,这是就要用到了@PostConstruct这个注解了。