Search code examples
javaspring-mvcapplicationcontextspring-4tomcat8

How to create Spring(4) XML based WebApplicationContext in an embedded Servlet 3 environment using a programmatically created parent context?


i like to create a Spring WebApplicationContext using a WebApplicationInitializer in an embedded Tomcat 8 container and also want to provide a parent context for this WebApplicationContext.

What i do in my code is:

ApplicationContext context = new ClassPathXmlApplicationContext(new
    String[{"samples/context.xml"});
// ... here i do funny things with the context ...

than i create a Tomcat 8 instance:

Tomcat t = new Tomcat()
// ... some configuration ...
t.start();

so i am searching for an implementation of 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?
}

i don't want to use the classic ContextLoaderListener in web.xml to create the WebAppContext at Tomcat startup (even thoug it would be interesting how to tell the loader to use a pre-built provided context as parent for the new context)

i also don't want to use the:

<import resource="classpath*:/META-INF/whatever/root/to/otherAppContext.xml" />

also i don't want to use the annotation driven approach using AnnotationConfigWebApplicationContext.

i also don't want to use the import - trick in my WebAppContext to import a XML defintion.

Tech used: Spring 4.0.3, Tomcat 8, Java 8SE

Any suggestions how to implement the onStartup(...) Method of my WebApplicationInitializer? I took a look at Spring explanation, didn't help me. Please provide concrete working code.

Thx,


Solution

  • This worked for me:

    @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,