简体   繁体   English

如何使用Spring @Configuration覆盖导入的资源?

[英]How to override an imported resource using Spring @Configuration?

Is it possible to override imported resources using Spring annotation configuration? 是否可以使用Spring注释配置覆盖导入的资源?

The configuration class: 配置类:

@Configuration
@ImportResource({"classpath:applicationContext.xml"})
public class CoreConfiguration {

    @Resource(name = "classA")
    private ClassA classA;

    @Bean(name = "nameIWantToOverride")
    private ClassB classB() {
       return new ClassB("different setting");
    }

}

The applicationContext.xml includes: applicationContext.xml包括:

<bean name="classA" class="a.b.c.ClassA">
     <property name="nameIWantToOverride" ref="classB" />
</bean>

If classA has a classB field but I want it to use the ClassB I define in my configuration class, is that possible? 如果classA有一个classB字段,但我希望它使用我在配置类中定义的ClassB,那可能吗? I tried switching the order but that didn't help. 我尝试切换顺序,但无济于事。 It seems XML takes precedence as when I run a simple test of instantiating the config, it never reaches the classB method. 似乎XML优先,因为当我运行实例化配置的简单测试时,它永远不会到达classB方法。 If I change the name so it doesn't match the bean in the xml file, then it does reach the classB method. 如果我更改名称以使其与xml文件中的bean不匹配,则它确实可以到达classB方法。

I've seen where it can work the other way: Can spring framework override Annotation-based configuration with XML-based configuration? 我已经看到它可以以其他方式工作: spring框架可以用基于XML的配置覆盖基于注释的配置吗? but what about this direction? 但是这个方向呢? Since this is the newer way of doing things, I would think it you'd be able to do this. 由于这是更新的工作方式,因此我认为您可以做到。

What can I do to resolve this? 我该怎么解决?

Edit: Updated with XML. 编辑:更新为XML。 Assume classA has multiple fields but I just want to replace the one. 假设classA有多个字段,但我只想替换一个字段。

You cannot override spring xml configuration using annotation. 您不能使用注释覆盖spring xml配置。

Spring XML configuration always takes precedence to annotation configuration Spring XML配置始终优先于注释配置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM