前言
springboot项目启动之后,加载我自定义的配置类的一些方法。
正文
1、 创建自定义类实现 CommandLineRunner接口,重写run()方法。springboot启动之后会默认去扫描所有实现了CommandLineRunner的类,并运行其run()方法。
@Component
@Order(2) //通过order值的大小来决定启动的顺序
public class AskForLeave implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
askForLeave();
}
public void askForLeave(){
System.out.println("项目启动了,执行了方法");
}
}
运行结果:
2、创建自定义类实现ApplicationRunner 接口,重写run()方法。
@Component
@Order(3)
public class Hello implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
hello();
}
public void hello(){
System.out.println("项目又启动了,这次使用的是:继承 ApplicationRunner");
}
}
结果如下:
关于二者的区别:
其实并没有什么区别,如果想获取更加详细的参数的时候,可以选择使用ApplicationRunner接口。其参数类型为:ApplicationArguments 。