For testing, I wanted the option to have the applicaitoncontext be modifyable.
Normally, I'd use the Spring4UnitRunner for testcases in combination with a @ConfigurationContext(...)
However, in this case, I wanted to modify the applicationcontext, or more precisely, I wanted to override a property, with a different value for each test.
(overriding the properties for the entire test with a property-file should be easy, using @TestPropertySource)
Injecting the applicationcontext didn't work, as we receive a GenericApplicationContext, which cannot be refreshed.
So, we create our own applicationcontext, update the properties, and refresh the context:
Important to note: localOverride to true, Order to highest, and ingoreunresolvable to true (which allows fallback to the existing properties)
Normally, I'd use the Spring4UnitRunner for testcases in combination with a @ConfigurationContext(...)
However, in this case, I wanted to modify the applicationcontext, or more precisely, I wanted to override a property, with a different value for each test.
(overriding the properties for the entire test with a property-file should be easy, using @TestPropertySource)
Injecting the applicationcontext didn't work, as we receive a GenericApplicationContext, which cannot be refreshed.
So, we create our own applicationcontext, update the properties, and refresh the context:
private ApplicationContext createApplicationContextWithProperties(String applicationContextXmlLocation, Map<String, Object> propertiesMap) {
ClassPathXmlApplicationContext overridenApplicationContext = new ClassPathXmlApplicationContext(applicationContextXmlLocation);
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
Properties properties = new Properties();
properties.putAll(propertiesMap);
configurer.setProperties(properties);
configurer.setOrder(PriorityOrdered.HIGHEST_PRECEDENCE);
configurer.setLocalOverride(true);
configurer.setIgnoreUnresolvablePlaceholders(true);
overridenApplicationContext.addBeanFactoryPostProcessor(configurer);
overridenApplicationContext.refresh();
return overridenApplicationContext;
}
Important to note: localOverride to true, Order to highest, and ingoreunresolvable to true (which allows fallback to the existing properties)
Reacties
Een reactie posten