springboot2启动时执行,初始化(或定时任务)servletContext问题
作者:亦寒2017 发布时间:2022-10-18 13:14:30
springboot2启动时执行,初始化(或定时任务)servletContext
需求:springboot 启动后自动执行,初始化数据,并将数据放到 servletContext 中。
首先,不可使用 ServletContextListener 即不能用 @WebListener ,因为 servlet 容器初始化后,spring 并未初始化完毕,不能使用 @Autowired 注入 spring 的对象。
代码如下:
可以实现 ApplicationListener
@Component
public class SettingDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
WebApplicationContext webApplicationContext =
(WebApplicationContext)contextRefreshedEvent.getApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
servletContext.setAttribute("key", "value");
}
}
使用注解注入
service
类里注入 servletContext
@Autowired private ServletContext servletContext;
service
类里要启动执行的方法加上注解
@PostConstruct
在定时任务里,也可以注入 servletContext,进行定时操作
@Component
public class MyTask {
@Autowired
private ServletContext servletContext;
// 秒 分 时 日 月 周
@Scheduled(cron = "0 * * * * *")
public void resetDays() {
// servletContext
}
}
springboot启动时初始化数据的几种方式
在我们用springboot搭建项目的时候,经常碰到在项目启动时初始化一些字典数据、地市数据、等各类需求,针对这种需求Spring与Spring boot为我们提供了以下几种方案供我们选择:
springboot提供的ApplicationRunner与CommandLineRunner接口
Spring Bean初始化的init-method、PostConstruct注解、
InitializingBean、BeanPostProcessor接口
Spring的事件机制: 实现 ApplicationListener 接口
一、ApplicationRunner与CommandLineRunner
如果需要在SpringApplication启动时执行一些特殊的代码,可以通过实现ApplicationRunner或CommandLineRunner接口,这两个接口都提供单一的run方法,且run方法仅在SpringApplication.run(…)完成之前调用。
区别:参数不一样,CommandLineRunner的参数是最原始的参数,没有进行任何处理,ApplicationRunner的参数是ApplicationArguments
ApplicationRunner接口只需要自己创建类实现ApplicationRunner接口
/**
* @author 重庆阿汤哥
* @Description: 测试
* @date 2021/11/26
*/
@Component
@Slf4j
public class ApplicationRunnerTest implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("ApplicationRunner init data.....");
}
}
CommandLineRunner
对于这个接口而言,我们可以通过Order注解或者使用Ordered接口来指定调用顺序,@Order()中的值越小,优先级越高
/**
* @author 重庆阿汤哥
* @Description: 测试
* @date 2021/11/26
*/
@Component
@Slf4j
@Order(1)
public class CommandLineRunnerTest implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("CommandLineRunner init data.....");
}
}
二、Spring Bean初始化的InitializingBean,init-method和PostConstruct
InitializingBean接口、BeanPostProcessor接口
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet()方法。
在spring初始化bean的时候,如果bean实现了InitializingBean接口,在对象的所有属性被初始化后之后才会调用afterPropertiesSet()方法
/**
* @author 重庆阿汤哥
* @Description: 测试
* @date 2021/11/26
*/
@Component
@Slf4j
@Component
public class InitialingzingBeanTest implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
log.info("InitializingBean init....");
}
}
@PostConstruct
/**
* @author 重庆阿汤哥
* @Description: 测试
* @date 2021/11/26
*/
@Component
@Slf4j
public class DynamicRouteMonitor {
@PostConstruct
public void init() {
log.info("gateway route init...");
}
}
BeanPostProcessor接口
可以用于判断某些特定类加载完成后才能初始化数据的场景,只需要自己实现该接口中的方法进行前置条件判断
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
三、Spring的事件机制
在Spring中,默认对ApplicationEvent事件提供了如下支持:
ContextStartedEvent
:ApplicationContext启动后触发的事件ContextStoppedEvent
:ApplicationContext停止后触发的事件ContextRefreshedEvent
:ApplicationContext初始化或刷新完成后触发的事件;也就是容器初始化完成后调用。ContextClosedEvent
:ApplicationContext关闭后触发的事件;如web容器关闭时自动会触发spring容器的关闭。甚至大家听说过的钩子程序都是调用ctx.registerShutdownHook()进行注册虚拟机关闭。
利用ContextRefreshedEvent事件进行初始化操作
/**
* @author 重庆阿汤哥
* @Description:容器初始化完整后初始字典数据
* @date 2021/11/26 10:51
*/
@Component
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
//在容器加载完毕后获取dao层来操作数据库
ISysDictTypeService sysDictTypeService = (ISysDictTypeService) event.getApplicationContext().getBean(ISysDictTypeService.class);
sysDictTypeService.initDict();
IProvCityService provCityService = (IProvCityService) event.getApplicationContext().getBean(IProvCityService.class);
provCityService.initProvCity();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
这几种方式都可以满足我们日常开发的需求,针对具体场景使用对应的方案,在微服务应用中使用也较广泛。
来源:https://blog.csdn.net/m0_37202351/article/details/86180998
猜你喜欢
- 在项目中,分页是一个项目中必不可少的,它可以防止我们从数据库中进行大量数据查询时速度变慢,提高我们的查询效率。1、定义分页模型:PageMo
- feignclient https接口调用报证书错误问题最近在使用 feignclient 过程中,和第三方通过https 协议交互的时候,
- IDEA快速搭建spring boot项目1.创建项目老规矩,点击Create New Project2.编写控制器在com.demo.sp
- openFeign服务间调用保持请求头信息处理1、注意特殊情况,在定时任务或者内部之间调用,没有request的时候,不要处理直接返回。2、
- 多选和单选的不同之处单选的时候,选中一个就可以直接把结果返回,因此本身底部弹窗无需状态管理。但到多选的时候,需要知道当前选中的选项,有选项被
- 这篇文章主要介绍了Spring使用@Autowired为抽象父类注入依赖代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一
- 前言前面的篇幅里有提到通过InitializingBean和Disposable等接口可以对bean的初始化和销毁做一些自定义操作,那么有一
- 注解@Validated和BindingResult对入参非空校验在项目当中少不了入参校验,服务器和浏览器互不信任,不能因为前端加入参判断了
- 前言1、下面是一个效果展示;2、先抱怨一下,在博客上面的抄袭真的非常严重,为了实现一个图片滑动验证,我搜索了挺久的资料,不过内容翻来覆去就是
- 1. 背景在业务处理完之后,需要调用其他系统的接口,将相应的处理结果通知给对方,若是同步请求,假如调用的系统出现异常或是宕机等事件,会导致自
- final File imageFile = new File(getCacheDir().getPath() + "/img/&
- 一、解决的痛点 1、免搭建后端开发环境。 &n
- 面试题1:说一下抽象类和接口有哪些区别?正经回答:抽象类和接口的主要区别:从设计层面来说,抽象类是对类的抽象,是一种模板设计;接口是行为的抽
- 使用Spring data JPA开发已经有一段时间了,这期间学习了一些东西,也遇到了一些问题,在这里和大家分享一下。前言:Spring d
- 先看下效果:两种需求场景:1.广告页3s后跳转到首页2.短信验证码60s倒计时第一种的话,根据需求我们可以知道,我们想要的效果就是3s结束做
- JavaWeb项目部署到服务器详细步骤本地准备在eclipse中将项目打成war文件:鼠标右键要部署到服务器上的项目导出项目数据库文件MyS
- 相信大家都经常使用String 的split方法,但是大家有没有遇到下面的这种情况:大家想想下面的代码执行结果是什么public stati
- paras.xml文件<?xml version="1.0" encoding="UTF-8"
- RocketMQ发送消息我们在使用RocketMQ发送消息时,一般都会使用DefaultMQProducer,类型的代码如下:Default
- @Configuration注解的类:/** * @Description 测试用的配置类 * @Author 弟中弟 * @CreateT