本文的核心内容:项目启动后(Spring Boot 项目加载完成、所有由Spring管理的Bean创建完成),我们需要初始化一些数据。这时,我们有两种方式可以解决这个问题。
一:CommandLineRunner和ApplicationRunner 接口
CommandLineRunner接口
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CommandLineRunnerBean implements CommandLineRunner {
//注入相关Bean
@Override
public void run(String... args) {
//do something
}
}
ApplicationRunner 接口
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ApplicationRunnerBean implements ApplicationRunner {
//注入相关Bean
@Override
public void run(ApplicationArguments arg0) throws Exception {