Spring Boot的CommandLineRunner接口:项目启动后执行初始化语句

166 阅读1分钟

创建类实现CommandLineRunner接口

@Component
public class Xxx implements CommandLineRunner {
    @Override
    public void run(String... args) {
        // code here
    }
}

项目启动后就会执行run()方法中的语句
也可以让启动类实现CommandLineRunner接口,这样则不需要@Component注解

@SpringBootApplication
public class XxxAplication implements CommandLineRunner {
    public static void main(String[] args) { SpringApplication.run(XxxApplication.clss, args); }
    
    @Override
    public void run(String... args) {
        // code here
    }
}