在运行时动态添加spring上下文配置?

Ami*_*far 6 java junit spring

在spring/junit中,您可以使用@ContextConfiguration诸如之类的加载应用程序上下文文件

@ContextConfiguration({"classpath:a.xml", "classpath:b.xml"})
Run Code Online (Sandbox Code Playgroud)

我有一个要求,如果我在测试类上看到一个特殊的注释,那么动态添加另一个XML上下文文件.例如:

@ContextConfiguration({"classpath:a.xml", "classpath:b.xml"})
@MySpecialAnnotation 
class MyTest{
...
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我会寻找@MySpecialAnnotation并添加special-context.xml.做这个的最好方式是什么?我已经看了一段时间,看起来像我自己的子类ContextLoader,这是@ContextConfiguration最好的方法之一的参数之一?它是否正确?有一个更好的方法吗?

Ami*_*far 2

事实证明,最好的解决方案是创建我自己的ContextLoader。我通过扩展抽象的来做到这一点。

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
    }
}
Run Code Online (Sandbox Code Playgroud)