Spring项目实例—项目启动后执行一次

简介: 1、实现接口ApplicationListener2、重写方法onApplicationEvent(ContextRefreshedEvent event)3、在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。

1、实现接口ApplicationListener
2、重写方法onApplicationEvent(ContextRefreshedEvent event)
3、在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。

这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理,修改后代码

例:

@Component
public class DevicePerfectRateTestData implements ApplicationListener<ContextRefreshedEvent> {
  public void onApplicationEvent(ContextRefreshedEvent event){

//root application context 没有parent,他就是老大.
//需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。        if(event.getApplicationContext().getParent() == null){
            insertTestDataOfDeviceSYSProduct();
        }
    }
}
相关文章
|
1天前
|
IDE Java Spring
Spring Boot中的多模块项目构建
Spring Boot中的多模块项目构建
|
2天前
|
安全 Java Maven
Spring Boot项目的模块化设计与架构
Spring Boot项目的模块化设计与架构
|
4天前
|
Java 开发者 Spring
Spring项目中Ordered接口的应用:全局过滤器(GlobalFilter)的顺序控制
Spring项目中Ordered接口的应用:全局过滤器(GlobalFilter)的顺序控制
11 2
|
5天前
|
IDE Java 机器人
Spring Boot中的多模块项目构建
Spring Boot中的多模块项目构建
|
7天前
|
消息中间件 XML Java
经验大分享:spring项目在启动的时候执行方法初始化
经验大分享:spring项目在启动的时候执行方法初始化
|
8天前
|
Java Maven 开发工具
IDEA使用Spring Initializr流畅的创建springboot项目
IDEA使用Spring Initializr流畅的创建springboot项目
32 0
|
8天前
|
运维 Java 测试技术
Spring运维之boo项目表现层测试加载测试的专用配置属性以及在JUnit中启动web服务器发送虚拟请求
Spring运维之boo项目表现层测试加载测试的专用配置属性以及在JUnit中启动web服务器发送虚拟请求
15 3
|
8天前
|
运维 Java 关系型数据库
Spring运维之boot项目bean属性的绑定读取与校验
Spring运维之boot项目bean属性的绑定读取与校验
13 2
|
8天前
|
缓存 运维 Java
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
14 0
|
8天前
|
XML 运维 Java
Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
13 1