为什么Spring @Configuration类继承无法按预期工作?

问题描述:

我有一个抽象的Spring配置类,其中包含一个普通的bean:

I have an abstract Spring configuration class that includes a common bean:

public abstract class AbstractConfig {
    @Bean
    public CommonBean commonBean {
        CommonBean commonBean = new CommonBean();
        commonBean.specifics = getSpecifics();
    };

    public abstract String getSpecifics();
}

普通bean的细节由其子类设置:

The common bean's specifics are set by its subclasses:

package realPackage;
@Configuration
public class RealConfig extends AbstractConfig {
    @Override
    public String getSpecifics() {
        return "real";
    }
}

...和...

package testPackage;
@Configuration
@ComponentScan(basePackages = {"testPackage", "realPackage" })
public class TestConfig extends AbstractConfig {
    @Override
    public String getSpecifics() {
        return "test";
    }
}

我的测试仅需要使用 TestConfig ,而不必了解 RealConfig (但确实需要访问 realPackage 中的其他组件).它开始于:

My test only needs to use the TestConfig and shouldn't know about the RealConfig (but does need access to other components in realPackage). It begins:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class MyIntegrationTestIT { //... }

使用上面的代码,它可以按预期工作,并使用"test" 细节.但是,如果我颠倒了 @ComponentScan 中的程序包顺序,则会使用"real" 特定内容来代替.这让我感到困惑-是否在指定 TestConfig ,因此确定它应该在此上调用重写的方法吗?谁能建议Spring这样做的原因以及如何解决?

With the code above, this works as expected and uses the "test" specifics. But if I reverse the order of packages in the @ComponentScan, the "real" specifics are used instead. This is baffling me - am specifying the TestConfig so surely it should be calling the overridden method on this? Could anyone advise as to the reasons Spring does this and how it might be resolved?

事实证明,该问题是由于我对如何使用 @Configuration 注释的Bean缺乏理解所致.组件扫描.

The issue turned out to be due to a lack of understanding on my part of how beans annotated with @Configuration are picked up by a component scan.