Reputation: 34150
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?
Upvotes: 7
Views: 9461
Reputation: 34150
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
}
}
Upvotes: 2
Reputation: 7218
Perhaps you can make use of Spring 3.1 Profiles to achieve this.
If you put the beans defined in special-context.xml into a profile called special you can activate the special profile using @Profile("special) on your class.
This would remove the need for your special annotation entirely.
Upvotes: 2