Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding spring context configuration at runtime?

Tags:

java

junit

spring

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?

like image 425
Amir Raminfar Avatar asked Nov 09 '11 20:11

Amir Raminfar


1 Answers

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
    }
}
like image 131
Amir Raminfar Avatar answered Nov 14 '22 23:11

Amir Raminfar