2012-07-25 72 views
2

我正在設置一個實用程序,使我們可以加載基於註釋的配置來覆蓋XML配置(用於測試)。我已經嘗試了許多不同的設置,但是這是我已經得到了工作只有一個:彈出混合XML /批註配置並覆蓋

GenericApplicationContext firstCtx = new GenericApplicationContext(); 

XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(firstCtx); 
xmlReader.loadBeanDefinitions("applicationContext.xml"); 

GenericApplicationContext ctx = new GenericApplicationContext(); 

AnnotatedBeanDefinitionReader annotatedReader = new AnnotatedBeanDefinitionReader(ctx); 
annotatedReader.register(SomeConfigClass.class); 

ctx.refresh(); 

for (String currBeanName : firstCtx.getBeanDefinitionNames()) 
{ 
    if (!ctx.containsBeanDefinition(currBeanName)) 
    { 
     ctx.registerBeanDefinition(currBeanName, firstCtx.getBeanDefinition(currBeanName)); 
    } 
} 

儘管這在技術上確實工作,這似乎是一個非常麻煩的方式來做到這一點。有沒有更好的方法來通過基於XML的配置加載基於註釋的配置?

謝謝!

回答

0

我認爲一個簡單的方法是簡單地聲明SomeConfigClass爲你的應用環境和SomeConfigClass配置的豆中的豆將在接線。

<bean class="..SomeConfigClass"/> 

或者<context:component-scan base-package="package of SomeConfigClass"/>

或者倒過來,在SomeClassClass中,做@ImportResource("applicationContext.xml")

+0

感謝您的迴應!我嘗試了'@ImportResource'註釋,但不幸的是XML會覆蓋基於Annotation的配置。我考慮過進行組件掃描,但這需要所有測試使用相同的覆蓋,我們希望能夠在每個測試類的基礎上覆蓋單個bean。 – 2012-07-26 13:24:58