【问题标题】:Spring Bean Creation of one Interface depending on ConditionSpring Bean 根据条件创建一个接口
【发布时间】:2020-10-05 17:50:48
【问题描述】:

我的目标是根据类路径中类的属性或存在来使用两个 bean 实现。我尝试的是 ConditionalOnPropery,见下文,但没有奏效。

我有一个类似的界面

public interface ApplicationConfigurator {

    void configure(WicketApplication wicketApplication);

}

还有两个实现类

@Component
@ConditionalOnProperty(
        value = "environment",
        havingValue = "client",
        matchIfMissing = false
)
public class OfflineApplicationConfigurator implements ApplicationConfigurator {

    @Override
    public void configure(WicketApplication wicketApplication) {

    }
}

@Component
    @ConditionalOnProperty(
            value = "environment",
            havingValue = "server",
            matchIfMissing = false
    )
public class OnlineApplicationConfigurator implements ApplicationConfigurator {

    @Autowired
    private LsgConfiguration configuration;

    @Override
    public void configure(WicketApplication wicketApplication) {
        try {
            Class.forName("org.apache.catalina.core.StandardServer");
            configuration.setHttpSchema(new TomcatConnectors().getHttpConnector().getScheme());
        } catch (ClassNotFoundException | ApplicationConfigurationException exception) {
            configuration.setHttpSchema("http");
        }
    }
}

我的配置是基于 xml 的,看起来像:

<bean id="onlineApplicationConfigurator" class="com.kion.lsg.service.core.web.config.OnlineApplicationConfigurator"/>
<bean id="offlineApplicationConfigurator" class="com.kion.lsg.service.core.web.config.OfflineApplicationConfigurator"/>

现在我收到错误消息:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [....service.core.web.config.ApplicationConfigurator] is defined: expected single matching bean but found 2: onlineApplicationConfigurator,offlineApplicationConfigurator

感谢任何帮助

【问题讨论】:

    标签: java spring conditional-statements


    【解决方案1】:

    您是否在 application.yml 中指定条件变量“环境”?由于这两个都是组件,它应该自动扫描,无需在 XML 文件中声明。您可以启用调试模式以查看条件评估报告,这将更有洞察力。

    【讨论】:

    • 我在 tomat 的 context.xml 和/或 -Denvironment=server 中指定它。我的旧遗留项目中有基于 xml 的配置
    • 你试过调试模式,它给出条件评估报告吗?您使用的是什么版本的 Spring Boot?尝试打印环境变量的值,它会被拾取吗?
    猜你喜欢
    • 2019-09-08
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多