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

时间:2011-11-09 20:29:45

标签: java spring junit

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

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

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

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

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

2 个答案:

答案 0 :(得分:2)

也许您可以使用Spring 3.1 Profiles来实现这一目标。

如果将special-context.xml中定义的bean放入名为special的配置文件中,则可以在类上使用@Profile(“special”)激活特殊配置文件。

这将完全取消对您的特殊注释的需要。

答案 1 :(得分: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
    }
}
相关问题