当我们最近将第二个spring应用程序部署到同一个Tomcat时,我们遇到了意外交互的问题。
正如经常发生的那样,这打开了一大堆关于我如何创建弹簧背景的蠕虫。这不是一个春季启动应用程序。
在Spring中使用Servlet 3.0初始化的例子并不缺乏。但是我找不到一个使用Spring配置文件和@Configuration注释的上下文初始化。
经过多次痛苦,我确定了这个:
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("/");
唯一的问题是根上下文@configuration文件被“处理”了两次。一旦被扫描,但在实例化ContextLoaderListener时再次被扫描。我使用引号是因为第一次进行了一些初始化但是上下文没有处于可用状态。
我玩了context.refresh(),但这让事情变得更糟。
所有这些都会导致一些奇怪的问题,尤其是在根上下文中使用EHCache。总的来说,我可以忽略它。但似乎应该有一种方法让Spring只扫描每个上下文一次 - 并且仍然支持Profiles。但我没有想法。