Spring Boot开机启动实现
在SpringBoot调用main()后执行的代码,一般用于系统环境的检索
Springboot给我们提供了两种“开机启动”某些方法的方式:
ApplicationRunner
和CommandLineRunner
ApplicationRunner和CommandLineRunner区别:
CommandLineRunner接口的run()方法接收String数组作为参数,即是最原始的参数,没有做任何处理
ApplicationRunner接口的run()方法接收ApplicationArguments对象作为参数,是对原始参数做了进一步的封装
实现如下:
新建类继承 ApplicationRunner 实现run()
同时需要添加@Component注解把类交给IOC管理
如果出现多个ApplicationRunner 的实现类需要添加@Order 定义他们的执行顺序
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Component
public class TestRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("自启动程序");
}
}