概述
如果涉及到系统任务,例如在项目启动阶段要做一些数据初始化操作,这些操作有一个共同的特点,只在项目启动时进行,以后都不再执行,这里,容易想到web基础中的三大组件( Servlet、Filter、Listener )之一 Listener ,这种情况下,一般定义一个 ServletContextListener,然后就可以监听到项目启动和销毁,进而做出相应的数据初始化和销毁操作如果使用了 Spring Boot,那么我们可以使用更为简便的方式。Spring Boot 中针对系统启动任务提供了两种解决方案,分别是 CommandLineRunner 和 ApplicationRunner,分别来看。CommandLineRunner
@Component @Order(100) public class MyCommandLineRunner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { } } // run 方法的参数,来自于项目的启动参数,即项目入口类中,main方法的参数会被传到这里。ApplicationRunner
ApplicationRunner 和 CommandLineRunner 功能一致,用法也基本一致,唯一的区别主要体现在对参数的处理上,ApplicationRunner 可以接收更多类型的参数(ApplicationRunner 除了可以接收 CommandLineRunner 的参数之外,还可以接收 key/value 形式的参数)。 @Component @Order(98) 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)); } } args.getNonOptionArgs();可以用来获取命令行中的无key参数(和CommandLineRunner一样)。args.getOptionNames();可以用来获取所有key/value形式的参数的key。args.getOptionValues(key));可以根据key获取key/value 形式的参数的value。args.getSourceArgs(); 则表示获取命令行中的所有参数。