在之前的Servlet项目中,如果在项目启动阶段要做一些数据初始化操作,一般定义一个 ServletContextListener,然后就可以监听到项目启动和销毁,进而做出相应的数据初始化和销毁操作,例如下面这样:
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//在这里做数据初始化操作
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//在这里做数据备份操作
}
}
如果使用了 Spring Boot,可以使用 CommandLineRunner 或 ApplicationRunner。
使用 CommandLineRunner 时,需要自定义CommandLineRunner:
@Component
@Order(100)
public class MyCommandLineRunner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
}
}
添加 @Order注解,表示这个启动任务的执行优先级,因为在一个项目中,启动任务可能有多个,所以需要有一个排序。@Order 注解中,数字越小,优先级越大,默认情况下,优先级的值为 Integer.MAX_VALUE,表示优先级最低。当项目启动时,run方法会被自动执行。run 方法的参数,来自于项目的启动参数,即项目入口类中,main方法的参数会被传到这里。
ApplicationRunner 和 CommandLineRunner 功能一致,用法也基本一致,唯一的区别主要体现在对参数的处理上,ApplicationRunner 可以接收更多类型的参数(ApplicationRunner 除了可以接收 CommandLineRunner 的参数之外,还可以接收 key/value形式的参数)。
@Component
@Order(100)
public class MyApplicationRunner1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
List<String> nonOptionArgs = args.getNonOptionArgs();
System.out.println("MyApplicationRunner1>>>"+nonOptionArgs);
Set<String> optionNames = args.getOptionNames();
for (String key : optionNames) {
System.out.println("MyApplicationRunner1>>>"+key + ":" + args.getOptionValues(key));
}
String[] sourceArgs = args.getSourceArgs();
System.out.println("MyApplicationRunner1>>>"+Arrays.toString(sourceArgs));
}
}
当项目启动时,这里的 run 方法就会被自动执行,关于 run 方法的参数 ApplicationArguments :
args.getNonOptionArgs();可以用来获取命令行中的无key参数(和CommandLineRunner一样)。
args.getOptionNames();可以用来获取所有key/value形式的参数的key。
args.getOptionValues(key));可以根据key获取key/value 形式的参数的value。
args.getSourceArgs(); 则表示获取命令行中的所有参数。
ApplicationRunner 定义完成后,传启动参数也是两种方式,参数类型也有两种,第一种和 CommandLineRunner 一致,第二种则是 -–key=value 的形式。