1

When we recently deployed a second spring application to the same Tomcat we ran into problems with unexpected interaction.

As so often happens this opened a very large can of worms concerning how I have been creating my spring context. This is NOT a spring boot application.

There is no shortage of examples of using Servlet 3.0 initialization in Spring. However I cannot find a single one that uses Spring profiles and @Configuration annotation based context initialization.

After much pain I settled on this:

AnnotationConfigWebApplicationContext rootApplicationContext = new AnnotationConfigWebApplicationContext();

    String [] activeProfiles = {"root","oracle"};
    rootApplicationContext.getEnvironment().setActiveProfiles(activeProfiles);
    rootApplicationContext.scan("com.xxx.restserver.config");


    // Create the dispatcher servlet's application context

    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    String[] dispatcherActiveProfiles = {"web"};
    dispatcherContext.getEnvironment().setActiveProfiles(dispatcherActiveProfiles);
    dispatcherContext.setParent(rootApplicationContext);
    dispatcherContext.scan("com.xxx.restserver.config");

    // Managed the lifecycle of the application context
    servletContext.addListener(new ContextLoaderListener(rootApplicationContext));


    // Register and map the dispatcher Servlet
    ServletRegistration.Dynamic dispatcher =
        servletContext.addServlet("Dispatcher", new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

The only problem is that the root context @configuration files are "processed" twice. Once when scanned but then again when the ContextLoaderListener is instantiated. I use quotes because the first time some of the initialization takes place but the context is not left in a usable state.

I played around with context.refresh() but that made matters much worse.

All this causes a few odd problems, most notably with EHCache in the root context. Overall I COULD just ignore it. But it seems there should be a way to get Spring to scan each context exactly once -- AND still support Profiles. But I am out of ideas.

Terry
  • 911
  • 10
  • 26

0 Answers0