我喜欢在嵌入式 Tomcat 8 容器中使用 WebApplicationInitializer 创建 Spring WebApplicationContext,并且还想为此提供一个父上下文 WebApplicationContext.
我在我的代码中所做的是:
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[{"samples/context.xml"});
// ... here i do funny things with the context ...
比我创建一个 Tomcat 8 实例:
Tomcat t = new Tomcat()
// ... some configuration ...
t.start();
所以我正在寻找 WebApplicationInitializer 的实现:
@Override
public void onStartup(final ServletContext servletContext) throws ServletException
{
SpringContext parentContext = ... obtain parent, i know how ...
WebAppContext webCtx = new WebAppContext("classpath:sample/web.xml",
parentContext); // how can i do this?
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(webCtx)); // correct?
// now create dispatcher servlet using WebAppContext as parent
DispatcherServlet servlet = ... perform creation ...
// how?
}
我不想在 web.xml 中使用经典的 ContextLoaderListener 在 Tomcat 启动时创建 WebAppContext(尽管如何告诉加载程序会很有趣使用预构建提供的上下文作为新上下文的父上下文)
我也不想使用:
<import resource="classpath*:/META-INF/whatever/root/to/otherAppContext.xml" />
我也不想使用使用AnnotationConfigWebApplicationContext 的注解驱动方法。
我也不想使用我的 WebAppContext 中的导入技巧来导入 XML 定义。
使用的技术:Spring 4.0.3、Tomcat 8、Java 8SE
有什么建议如何实现我的WebApplicationInitializer 的onStartup(...) 方法?我看了一下 Spring explanation ,没有帮助我。 请提供具体的工作代码。
谢谢,
最佳答案
这对我有用:
@Override
public void onStartup(final ServletContext servletContext) throws ServletException
{
final ApplicationContext parent = new ClassPathXmlApplicationContext(new String[
{"/com/mydomain/root.context.xml"});
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocation("classpath:/com/mydomain/childContext.xml");
context.setParent(parent);
ConfigurableWebApplicationContext webappContext = (ConfigurableWebApplicationContext)
context;
webappContext.setServletContext(servletContext);
webappContext.refresh();
servletContext.addListener(new ContextLoaderListener(webappContext));
// ... register dispatcher servlets here ...
}
HTH,
关于java - 如何使用以编程方式创建的父上下文在嵌入式 Servlet 3 环境中创建基于 Spring(4) XML 的 WebApplicationContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23343745/