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);
    }
}

 

转载于:https://www.cnblogs.com/stonesingsong/p/7957258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值