2011-11-09 30 views
6

在春天/ junit的,你可以使用@ContextConfiguration這樣在運行時動態添加spring上下文配置?

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

我有一個要求,在那裏,如果我看到一個測試類特殊的註釋,然後動態地添加其他的XML上下文文件加載應用程序上下文文件。例如:

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

在上面的例子中,我會找@MySpecialAnnotation,並添加special-context.xml也。做這個的最好方式是什麼?我已經看了這一段時間,它似乎是分類我自己的ContextLoader這是@ContextConfiguration的參數之一是最好的方法?它是否正確?有一個更好的方法嗎?

+0

你所說的動態的意思。註釋是靜態的,它不在運行時更改? – Ralph

+0

很明顯,這是我想解決的問題。我想動態地添加一個新的上下文到彈出加載的文件列表。 –

+0

但是註釋的含義是什麼?什麼應該觸發「現在添加上下文x」? – Ralph

回答

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 
    } 
} 
+0

如何添加和創建一個相同的測試用例(不是套件,但需要測試用例)來交叉檢查和驗證? – Kathir

2

也許你可以使用Spring 3.1 Profiles來實現這一點。

如果你把在特殊context.xml中定義的豆成一個稱爲特殊的個人資料,你可以在你的類使用@profile(「特)激活特定的配置文件。

這將消除需要爲您的特殊註釋完全。

相關問題