因项目集成了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{ @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);
}
}
利用CommandLineRunner、EnvironmentAware在Spring boot启动时执行初始化代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
//如果有多个这样的类时,可以通过Order指定执行顺序,数值越小执行优先级越高
@Order(value = 0)
public class InitSystemConfig implements CommandLineRunner, EnvironmentAware {
/*
* 在服务启动后执行,会在@Bean实例化之后执行,故如果@Bean需要依赖这里的话会出问题
*/
@Override
public void run(String... args) {
//这里可以根据数据库返回结果创建一些对象、启动一些线程等
}
/*
* 在SystemConfigDao实例化之后、@Bean实例化之前执行
* 常用于读取数据库配置以供其它bean使用
* environment对象可以获取配置文件的配置,也可以把配置设置到该对象中
*/
@Override
public void setEnvironment(Environment environment) {
}
}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。