• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解SpringBoot程序启动时执行初始化代码

springboot 搞代码 4年前 (2022-01-05) 52次浏览 已收录 0个评论

这篇文章主要介绍了详解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 { @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) { } }

以上就是来源gaodaimacom搞#^代%!码&网详解SpringBoot程序启动时执行初始化代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解SpringBoot程序启动时执行初始化代码

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址