将getContextLoader替换为已弃用的Spring 3到Spring 4

mxg2im7a  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(138)

我有一段代码可以在Spring 3中使用:

public class WebConsoleStarter extends ContextLoaderListener {

    private static final Logger LOG = LoggerFactory.getLogger(WebConsoleStarter.class);

    public void contextInitialized(ServletContextEvent event) {
        ...
        super.contextInitialized(event);
      initializeWebClient(event.getServletContext() ,  getContextClassLoader().getCurrentWebApplicationContext());
      ...
    }

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

}

但是这段代码不能在Spring 4上运行,因为getContextLoader已经不存在了。我看到有一个“getContextClassLoader”方法,但是看起来不一样。
我在Spring文档中看到了以下短语:
getContextLoader()支持简单地对ContextLoaderListener本身进行子类化(从Spring 3.0开始,它扩展了ContextLoader)
但是我不明白我在代码中到底要做什么:/

j8yoct9x

j8yoct9x1#

我只是把旧的替换为:

public class WebConsoleStarter extends ContextLoaderListener {

    private static final Logger LOG = LoggerFactory.getLogger(WebConsoleStarter.class);

    public void contextInitialized(ServletContextEvent event) {
        ...
        super.contextInitialized(event);
      initializeWebClient(event.getServletContext() ,  ContextLoader.getCurrentWebApplicationContext());
      ...
    }

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

}

相关问题