Introduce ConfigurableEnvironment#merge

Prior to this change, AbstractApplicationContext#setParent replaced the
child context's Environment with the parent's Environment if available.
This has the negative effect of potentially changing the type of the
child context's Environment, and in any case causes property sources
added directly against the child environment to be ignored. This
situation could easily occur if a WebApplicationContext child had a
non-web ApplicationContext set as its parent. In this case the parent
Environment type would (likely) be StandardEnvironment, while the child
Environment type would (likely) be StandardServletEnvironment. By
directly inheriting the parent environment, critical property sources
such as ServletContextPropertySource are lost entirely.

This commit introduces the concept of merging an environment through
the new ConfigurableEnvironment#merge method. Instead of replacing the
child's environment with the parent's,
AbstractApplicationContext#setParent now merges property sources as
well as active and default profile names from the parent into the
child. In this way, distinct environment objects are maintained with
specific types and property sources preserved. See #merge Javadoc for
additional details.

Issue: SPR-9444, SPR-9439
This commit is contained in:
Chris Beams
2012-05-26 14:09:21 +03:00
parent 5874383ef0
commit 9fcfd7e827
5 changed files with 92 additions and 7 deletions

View File

@@ -48,6 +48,7 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
protected ConfigurableApplicationContext createContext() throws Exception {
InitAndIB.constructed = false;
root = new XmlWebApplicationContext();
root.getEnvironment().addActiveProfile("rootProfile1");
MockServletContext sc = new MockServletContext("");
root.setServletContext(sc);
root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"});
@@ -69,6 +70,7 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
});
root.refresh();
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.getEnvironment().addActiveProfile("wacProfile1");
wac.setParent(root);
wac.setServletContext(sc);
wac.setNamespace("test-servlet");
@@ -77,8 +79,11 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
return wac;
}
public void testEnvironmentInheritance() {
assertThat(this.applicationContext.getEnvironment(), sameInstance(this.root.getEnvironment()));
public void testEnvironmentMerge() {
assertThat(this.root.getEnvironment().acceptsProfiles("rootProfile1"), is(true));
assertThat(this.root.getEnvironment().acceptsProfiles("wacProfile1"), is(false));
assertThat(this.applicationContext.getEnvironment().acceptsProfiles("rootProfile1"), is(true));
assertThat(this.applicationContext.getEnvironment().acceptsProfiles("wacProfile1"), is(true));
}
/**