ApplicationRunner 和 CommandLineRunner的使用
使用场景:
如果我们需要在 SpringApplication 启动后自动运行一些特定的代码,我们可以使用这两个接口,这两个接口都是函数式接口有且只有一个run方法,通过实现这两个接口,我们可以在run方法中编写一些代码,这个run方法会在SpringApplication应用启动完成之后自动的执行,同时为了确保实现了这两个接口的实现类能够自动生效,我们必须将该类注册成Bean组件,此外,我们也可以继续通过实现Ordered接口或者通过@Order注解来指定run方法的执行顺序,其中Order的值越小越先执行,参考如下:
@Component public class TestApplicationRunner implements ApplicationRunner, Ordered { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("【ApplicationRunner】这是使用ApplicationRunner接口实现的代码执行,Order值为0"); } @Override public int getOrder() { return 0; } }
@Order(value = 1) @Component public class TestCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("【CommandLineRunner】这是使用CommandLineRunner接口实现的代码执行,Order值为1"); } }
程序启动结果:
下一篇:
JAVA贪吃蛇(简易版)