Dynamically adding spring context configuration at runtime?

In spring / junit, you can load application context files using @ContextConfiguration , e.g.

 @ContextConfiguration({"classpath:a.xml", "classpath:b.xml"}) 

I have a requirement when I see a special annotation on a test class, then dynamically add another XML file. For instance:

 @ContextConfiguration({"classpath:a.xml", "classpath:b.xml"}) @MySpecialAnnotation class MyTest{ ... } 

In the above example, I would like to search @MySpecialAnnotation and add special-context.xml . What is the best way to do this? I looked at this for a while, and it seems that subclassing for my own ContextLoader , which is one of the @ContextConfiguration options, is the best approach? It's right? Is there a better way to do this?

+6
source share
2 answers

It turns out that the best solution is to create your own ContextLoader . I did this by expanding abstract.

 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 } } 
+2
source

Perhaps you can use Spring 3.1 Profiles to achieve this.

If you put the beans defined in special-context.xml in a profile called special, you can activate the special profile with @Profile ("special") in your class.

This completely eliminates the need for your special annotation.

+2
source

Source: https://habr.com/ru/post/901151/


All Articles