In spring/junit you can load application context files using @ContextConfiguration
such as
@ContextConfiguration({"classpath:a.xml", "classpath:b.xml"})
I have a requirement where if I see a special annotation on a test class then add another XML context file dynamically. For example:
@ContextConfiguration({"classpath:a.xml", "classpath:b.xml"})
@MySpecialAnnotation
class MyTest{
...
}
In the above example I would look for @MySpecialAnnotation
and add special-context.xml
also. What is the best way to do this? I have looked at this for a while and it seems like sub-classing my own ContextLoader
which is one of the parameters to @ContextConfiguration
is the best approach? Is this correct? Is there a better way to do this?
It turns out the best solution is to create my own ContextLoader. I did this by extending the abstract one.
public class MyCustomContextListener extends GenericXmlContextLoader implements ContextLoader {
@Override
protected String[] generateDefaultLocations(Class<?> clazz) {
List<String> locations = newArrayList(super.generateDefaultLocations(clazz));
locations.addAll(ImmutableList.copyOf(findAdditionalContexts(clazz)));
return locations.toArray(new String[locations.size()]);
}
@Override
protected String[] modifyLocations(Class<?> clazz, String... locations) {
List<String> files = newArrayList(super.modifyLocations(clazz, locations));
files.addAll(ImmutableList.copyOf(findAdditionalContexts(clazz)));
return files.toArray(new String[files.size()]);
}
private String[] findAdditionalContexts(Class<?> aClass) {
// Look for annotations and return 'em
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With