3

我正在设置一个实用程序,该实用程序允许我们加载基于注释的配置,该配置覆盖 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 的配置?

谢谢!

4

1 回答 1

0

我认为更简单的方法是SomeConfigClass在应用程序上下文中简单地声明为 bean,并且 SomeConfigClass 中配置的 bean 将被连接。

<bean class="..SomeConfigClass"/>

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

或者反过来,在 SomeClassClass 中,做@ImportResource("applicationContext.xml")

于 2012-07-25T23:40:03.803 回答