【发布时间】: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) {
}
}
【问题讨论】: