java - 如何使用以编程方式创建的父上下文在嵌入式 Servlet 3 环境中创建基于 Spring(4) XML 的 WebApplicationContext?

标签 java spring-mvc applicationcontext spring-4 tomcat8

我喜欢在嵌入式 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/

相关文章:

java - 为什么应用程序没有完成?

java - GridBagLayout 问题 : TextArea overlapping MenuBar

Java 垃圾收集器 :old generation becomes larger and larger and cannot be reclaimed

java - 即使一个 bean 在运行时出现错误,也确保 Spring 应用程序的其余部分运行

spring-mvc - spring boot测试无法注入(inject)TestRestTemplate和MockMvc

java - 使用 spring 和 hibernate 测试数据库连接

java - 使用 getValue 调用 Firebase 时,在类 org.json.JSONObject 上找不到要序列化的属性

java - 将参数传递给 threadpoolexecutor

spring - 具有 Spring 应用程序上下文的 JUnit 自定义运行器

java - 从 spring mvc 设置一个选择框值