没有合适的资源?快使用搜索试试~ 我知道了~
首页详解SpringBoot程序启动时执行初始化代码
详解SpringBoot程序启动时执行初始化代码
1.9k 浏览量
更新于2023-05-26
评论
收藏 47KB PDF 举报
主要介绍了详解SpringBoot程序启动时执行初始化代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
资源详情
资源评论
资源推荐

详解详解SpringBoot程序启动时执行初始化代码程序启动时执行初始化代码
主要介绍了详解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);
}
}
利用利用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需要依赖这里的话会出问题
*/














安全验证
文档复制为VIP权益,开通VIP直接复制

评论0