【问题标题】:Why do I need to set ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE in ServletContext?为什么需要在 ServletContext 中设置 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE?
【发布时间】:2015-12-28 19:16:18
【问题描述】:

我运行 Apache Tomcat 服务器并将我的应用程序作为 WAR 文件部署到它上面。在应用程序中,我使用 Apache CXF 创建了一个简单的 REST 资源。

web.xml 仅引用我的侦听器 (ContextListener) 类。 在这个类中,我创建了我的应用程序上下文,并添加了 CXF servlet。

如果我省略以下行,CXF 不会按预期工作,尽管资源 bean 已注册(“未找到服务。”)。

您能否解释一下这条线的作用、为什么需要它以及存在哪些替代方案?

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);

完整文件:

import xxx.resources.DefaultResource;
import org.apache.cxf.jaxrs.spring.SpringComponentScanServer;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;

public class ContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();

        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.setServletContext(servletContext);
        applicationContext.register(SpringComponentScanServer.class);
        applicationContext.register(DefaultResource.class);
        applicationContext.refresh();

        Class<CXFServlet> cxfServletClass = CXFServlet.class;
        ServletRegistration.Dynamic servletRegistration = servletContext.addServlet(cxfServletClass.getSimpleName(), cxfServletClass);
        servletRegistration.addMapping("/*");

        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }

}

【问题讨论】:

    标签: spring servlets cxf


    【解决方案1】:

    CXFServlet(使用 Spring)使用 Spring 的 WebApplicationContextUtils。此类又使用相同的键从 servlet 上下文中检索应用程序上下文。换句话说,由于我使用的是CXFServlet,所以我需要使用这个键来存储上下文。

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2013-10-13
      • 2016-09-28
      相关资源
      最近更新 更多