• 使用CommandLineRunner进行项目启动之后预加载数据


    在项目中有时需要在项目启动之后进行预加载数据(例如配置在数据中的常量数据),这是可以使用spring boot 提供的CommandLineRunner接口

    新建类实现CommandLineRunner接口,同时使用 @Component 注解

    @Component
    @Order(1)
    public class ConstantPreloading implements CommandLineRunner{
    
        private static final Logger LOGGER = LoggerFactory.getLogger(ConstantPreloading.class);
        
        @Override
        public void run(String... args) throws Exception {
            LOGGER.info("=========预加载一些常量信息==========");
        }
        
    }

    1、如果项目中需要多个预加载的动作,可以新建多个类并且实现CommandLineRunner接口,spring boot会自动扫描实现了CommandLineRunner接口的bean并依次执行。

    2、如果多个runner需要按优先级执行,这是可以使用@Order 注解,通过源码查看,order的值越小优先级越高(源码处排序方法 AnnotationAwareOrderComparator.sort(runners))。

    runner是由org.springframework.boot.SpringApplication.callRunners(ApplicationContext, ApplicationArguments) 执行的,部分代码如下

    private void callRunners(ApplicationContext context, ApplicationArguments args) {
            List<Object> runners = new ArrayList<>();
            runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
            runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
            AnnotationAwareOrderComparator.sort(runners);
            for (Object runner : new LinkedHashSet<>(runners)) {
                if (runner instanceof ApplicationRunner) {
                    callRunner((ApplicationRunner) runner, args);
                }
                if (runner instanceof CommandLineRunner) {
                    callRunner((CommandLineRunner) runner, args);
                }
            }
        }
  • 相关阅读:
    ORACLE11G 字符集更改(这里更改为AL32UTF8)
    linux 安装jdk1.8
    oracle的 listagg() WITHIN GROUP ()函数使用
    数据库事务中的隔离级别和锁以及spring @Transactional注解参数详解
    java读取Oracle中大字段数据(CLOB)的方法
    oracle常用函数_时间
    案例-todolist计划列表【添加计划】
    案例-todolist计划列表【显示列表】
    案例-todolist计划列表[基本代码]
    vue 阻止元素的默认行为
  • 原文地址:https://www.cnblogs.com/xiaoweiv/p/11237683.html
Copyright © 2020-2023  润新知