You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring 3升级至Spring 4:getContextLoader废弃后的代码适配咨询

解决Spring 4中ContextLoaderListener.getContextLoader()被移除的问题

Spring官方文档给出的提示已经点明了修改方向:

org.springframework.web.context.ContextLoaderListener.getContextLoader()
in favor of simply subclassing ContextLoaderListener itself (which extends ContextLoader, as of Spring 3.0)

意思是:Spring 3.0之后ContextLoaderListener本身就继承了ContextLoader类,原有的getContextLoader()方法被移除,你的子类(WebConsoleStarter)无需再通过该方法获取ContextLoader实例,直接调用继承自ContextLoader的方法即可。

修改后的代码

public class WebConsoleStarter extends ContextLoaderListener {
    
    private static final Logger LOG = LoggerFactory.getLogger(WebConsoleStarter.class);

    public void contextInitialized(ServletContextEvent event) {
        ...
        super.contextInitialized(event);
        // 直接调用getCurrentWebApplicationContext(),无需通过getContextLoader()
        initializeWebClient(event.getServletContext(), getCurrentWebApplicationContext());
        ...
    }

    private void initializeWebClient(ServletContext servletContext, WebApplicationContext context) {
        ConnectionFactory connectionFactory = (ConnectionFactory)context.getBean("connectionFactory");
        servletContext.setAttribute(WebClient.CONNECTION_FACTORY_ATTRIBUTE, connectionFactory);
        WebClient.initContext(servletContext);
    }
}

关键说明

  • 核心修改就是去掉getContextLoader().前缀,直接调用getCurrentWebApplicationContext()
  • 因为WebConsoleStarter继承了ContextLoaderListener,而ContextLoaderListener从Spring 3.0开始继承了ContextLoader,所以getCurrentWebApplicationContext()方法现在是当前类的继承方法,直接调用就能拿到原本需要通过getContextLoader()获取的上下文对象。

这个修改完全保留了原代码的业务逻辑,同时适配了Spring 4的API变更,能正常运行。

内容的提问来源于stack exchange,提问作者user2178964

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:41:08