当前位置: 首页 > article >正文

创建监听器报错“一个或多个listeners启动失败”

问题:

今天写一个需求,即当项目启动时,取出数据库的商品类型,供全局使用,但是出现了

 创建监听器报错“一个或多个listeners启动失败”。

解决:

错误示范:

我创建了两个IOC容器

@WebListener
public class ProductTypeListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
       
        //这是又从新创建了一个IOC容器,不可以     
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext_*.xml");
        ProductTypeService productTypeService = (ProductTypeService) context.getBean("ProductTypeServiceImpl");
        List<ProductType> typeList = productTypeService.getAll();
        //放入全局应用作用域中,供新增页面,修改页面,前台的查询功能提供全部商品类别集合
        servletContextEvent.getServletContext().setAttribute("typeList",typeList);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
 <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext_*.xml</param-value>
    </context-param>

正确示范:

@WebListener
public class ProductTypeListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        //拿到当前已经创建的IOC容器,而不是再创建一个
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
        ProductTypeService   productTypeService =(ProductTypeService) context.getBean("ProductTypeServiceImpl");
        List<ProductType> typeList = productTypeService.getAll();

        servletContextEvent.getServletContext().setAttribute("typeList",typeList);


    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

原因:

  • 重复加载 Spring 容器 ContextLoaderListener 已经通过 <context-param> 配置加载了 Spring 容器,而你又手动创建了一个新的容器,导致资源浪费。
  • Bean 不一致 :手动创建的容器与 ContextLoaderListener 加载的容器是独立的,可能导致 Bean 不一致(例如事务代理对象可能无法正常工作)。

http://www.kler.cn/a/557435.html

相关文章:

  • 区块链相关方法-PEST分析
  • 如何在cursor上使用 deepseek 模型
  • 深入理解 JSP 与 Servlet:原理、交互及实战应用
  • 怎么学习调试ISP的参数
  • 无法打开包括文件: “crtdbg.h”: No such file or directory
  • 《论单元测试方法及应用》审题技巧 - 系统架构设计师
  • Win10操作系统从机械硬盘HDD迁移到SSD固态硬盘
  • Redis-AOF
  • 进制转换--PAT(B)1022
  • Spring Cloud — Hystrix 服务隔离、请求缓存及合并
  • 什么是方法
  • 项目需求管理及其活动
  • 如何确定虚函数在虚函数表中的位置3 (Linux x64版本)
  • PySide6中如何实现TableWidget跨行列粘贴Excel表格内容
  • 深入理解 JUnit 的 @RunWith 注解与自定义 Runner
  • 【Kafka】Kafka高性能解读
  • DeepSeek 助力 Vue 开发:打造丝滑的二维码生成(QR Code)
  • 【Python爬虫(38)】解锁Scrapy - Redis:构建高效分布式爬虫
  • YOLOv8与DAttention机制的融合:复杂场景下目标检测性能的增强
  • 断开ssh连接程序继续运行