嵌套类@Configuration中的spring Bean Overriding 2.1.x @Bean创建失败,并显示“已经定义了具有该名称的bean”

时间:2018-10-11 07:53:15

标签: java spring spring-boot dependency-injection

升级到spring-boot 2.1.0.M4 Bean覆盖默认情况下处于禁用状态。如果您要依赖覆盖,则需要将spring.main.allow-bean-definition-overriding设置为true。

但是为什么在内部类中定义的Bean也被视为重复的Bean定义。这是错误吗?或有一些解释吗?

例如:

@Configuration
public class BusinessLogicConfig {

    @Configuration
    class BusinessLogicSourceConfig {
        @Bean
        public BusinessLogic businessLogic() {
            return new BusinessLogic("source");
        }
    }
}

在spring-boot 2.0.x之前可以正常工作

但是在使用例如spring-boot 2.1.0.M4在启动时给我一个错误:

The bean 'businessLogic', defined in class path resource [com/example/di/bootconfigs/BusinessLogicConfig$BusinessLogicTier1Config.class], could not be registered.
A bean with that name has already been defined in URL [jar:file:/.../di/build/libs/di-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/example/di/businesslogic/BusinessLogic.class]
and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

由于我显然只有一个bean定义(仅在内部@Configuration类中定义),对我来说似乎是个错误。

如果您问为什么我要使用嵌套的内部@Configuration类:

我经常有演示代码,演示了分布式系统的行为,其中我需要多个应用程序来演示事物。因为我不想拥有多个App代码,所以我只是用不同的配置文件启动同一个App,并且配置文件将“不同的业务逻辑”注入到我想“保持在一起”的一个文件中,例如:

@Configuration
public class BusinessLogicConfig {

    @Value("${app.info.instance_index}")
    private String instanceIndex;

    @Profile({ "source" }) // unused fake BusinessLogic for pure sources
    @Configuration
    class BusinessLogicSourceConfig {
        @Bean
        public BusinessLogic businessLogic() {
            return new BusinessLogic("source", instanceIndex);
        }
    }

    @Profile({ "sink" }) // unused fake BusinessLogic for pure sinks
    @Configuration
    class BusinessLogicSinkConfig {
        @Bean
        public BusinessLogic businessLogic() {
            return new BusinessLogic("sink", instanceIndex);
        }
    }

    @Profile({ "tier1" })
    @Configuration
    class BusinessLogicTier1Config {
        @Bean
        public BusinessLogic businessLogic() {
            return new BusinessLogic("tier1", instanceIndex);
        }
    }

    @Profile({ "tier2" })
    @Configuration
    class BusinessLogicTier2Config {
        @Bean
        public BusinessLogic businessLogic() {
            return new BusinessLogic("tier2", instanceIndex);
        }
    }

    @Profile({ "tier3" })
    @Configuration
    class BusinessLogicTier3Config {
        @Bean
        public BusinessLogic businessLogic() {
            return new BusinessLogic("tier3", instanceIndex);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

列出其不是@Configuration类的嵌套。 它是BusinessLogic类本身,它是一个名称为BusinessLogic的Bean,因为它是@Component。因此,上面创建了名为BusinessLogic的Bean的第二个版本。