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);
        }
    }
  • 相关阅读:
    Windows上git输错一次密码不在提示输入密码
    JSON Web Token 简介
    Springboot+Shiro+Jwt实现权限管理
    Springboot配置外部容器使用JNDI读取数据源
    Springboot解决Main方法启动无法注入JNDI
    Springboot2.1.6版本部署resin4.0.62
    Java解决多线程无法@Autowired注入,手动获取Bean对象
    Linux设置Vim显示行号
    Linux使用wget后台下载
    排查生产环境CPU过高的问题
  • 原文地址:https://www.cnblogs.com/stonesingsong/p/7957258.html
Copyright © 2011-2022 走看看