系统任务: 在项目启动阶段要做一些数据初始化操作, 这些操作有一个共同的特点, 只在项目启动时进行, 以后都不再执行
web 基础中的三大组件 ( Servlet,Filter,Listener ), 通过 Listener 定义一个 ServletContextListener, 然后就可以监听到项目启动和销毁, 进而做出相应的数据初始化和销毁操作.
- public class MyListener implements ServletContextListener {
- @Override
- public void contextInitialized(ServletContextEvent sce) {
- // 在这里做数据初始化操作
- }
- @Override
- public void contextDestroyed(ServletContextEvent sce) {
- // 在这里做数据备份操作
- }
- }
Spring Boot 提供了两种解决方案, 分别是 CommandLineRunner 和 ApplicationRunner
SpringBoot CommandLineRunner
使用 CommandLineRunner 时, 自定义 MyCommandLineRunner 实现 CommandLineRunner 接口:
- @Component // @Compoent 注解将 MyCommandLineRunner 注册为 Spring 容器中的一个 Bean.
- @Order(100) //@Order 注解, 表示这个启动任务的执行优先级, 在一个项目中, 启动任务可能有多个, 所以需要有一个排序.@Order 注解中, 数字越小, 优先级越大, 默认情况下, 优先级的值为 Integer.MAX_VALUE, 表示优先级最低.
- public class MyCommandLineRunner implements CommandLineRunner {
- @Override
public void run(String... args) throws Exception { n 方法的参数, 来自于项目的启动参数, 即项目入口类中, main 方法的参数会被传到这里.
- // 启动任务的核心逻辑, 当项目启动时, run 方法会被自动执行.
- }
- }
- SpringBoot ApplicationRunner
ApplicationRunner 和 CommandLineRunner 功能一致, 用法也基本一致, 唯一的区别主要体现在对参数的处理上, ApplicationRunner 可以接收更多类型的参数 (ApplicationRunner 除了可以接收 CommandLineRunner 的参数之外, 还可以接收 key/value 形式的参数).
使用 ApplicationRunner , 自定义类实现 ApplicationRunner 接口, 组件注册以及组件优先级的配置都和 CommandLineRunner 一致, 如下:
- @Component
- @Order(98)
- public class MyApplicationRunner implements ApplicationRunner {
- @Override
- public void run(ApplicationArguments args) throws Exception {
- List<String> nonOptionArgs = args.getNonOptionArgs(); // 可以用来获取命令行中的无 key 参数 (和 CommandLineRunner 一样).
- System.out.println("MyApplicationRunner>>>"+nonOptionArgs);
- Set<String> optionNames = args.getOptionNames(); // 可以用来获取所有 key/value 形式的参数的 key.
- for (String key : optionNames) {
- System.out.println("MyApplicationRunner>>>"+key + ":" + args.getOptionValues(key)); // 可以根据 key 获取 key/value 形式的参数的 value.
- }
- String[] sourceArgs = args.getSourceArgs(); // 则表示获取命令行中的所有参数.
- System.out.println("MyApplicationRunner>>>"+Arrays.toString(sourceArgs));
- }
- }
java -jar devtools-0.0.1-SNAPSHOT.jar 三国演义 西游记 --age=99
来源: http://www.bubuko.com/infodetail-3433918.html