zoukankan      html  css  js  c++  java
  • SpringBoot程序启动时执行初始化代码

    因项目集成了Redis缓存部分数据,需要在程序启动时将数据加载到Redis中,即初始化数据到Redis。

    在SpringBoot项目下,即在容器初始化完毕后执行我们自己的初始化代码。

    第一步:创建实现ApplicationListener接口的类

    package com.stone;
    
    import com.stone.service.IPermissionService;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    /**
     * @author Stone Yuan
     * @create 2017-12-02 21:54
     * @description
     */
    public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            IPermissionService service = contextRefreshedEvent.getApplicationContext().getBean(IPermissionService.class);
            service.loadUserPermissionIntoRedis();
        }
    }

    注意:

    1、我们自己的初始化代码写在onApplicationEvent里;

    2、ContextRefreshedEvent是Spring的ApplicationContextEvent一个实现,在容器初始化完成后调用;

    3、以注解的方式注入我们需要的bean,会报空指针异常,因此需要以代码中的方式获取我们要的bean

    第二步:在SpringBootApplication中注册我们刚创建的类

    package com.stone;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class YwythApplication {
    
        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(YwythApplication.class);
            springApplication.addListeners(new ApplicationStartup());
            springApplication.run(args);
        }
    }
  • 相关阅读:
    为什么你SQL Server的数据库文件的Date modified没有变化呢?
    SQL Server中SELECT会真的阻塞SELECT吗?
    ORACLE从共享池删除指定SQL的执行计划
    flink DataStream API使用及原理
    漫谈九品中正制和现阶段阶层分层
    flink dataset api使用及原理
    从flink-example分析flink组件(3)WordCount 流式实战及源码分析
    TODO supply a title
    avalon2学习教程01
    avalon1与avalon2的异同点
  • 原文地址:https://www.cnblogs.com/stonesingsong/p/7957258.html
Copyright © 2011-2022 走看看