You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于配置属性条件化创建Spring Boot中的Bean

基于自定义配置属性条件化创建Spring Boot Bean

你可以直接使用Spring Boot提供的@ConditionalOnProperty注解实现需求,这个注解专门用于基于配置属性的条件化Bean创建,比@ConditionalOnExpression更直观简洁。

修改后的Bean代码

@Bean
@ConditionalOnProperty(name = "enable.userconnection", havingValue = "false", matchIfMissing = false)
public CachingConnectionFactory connectionFactory(AxonConnectionFactory axonConnectionFactory, Integer jmsSessionCacheSize) {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setTargetConnectionFactory(axonConnectionFactory);
    connectionFactory.setReconnectOnException(true);
    connectionFactory.setSessionCacheSize(jmsSessionCacheSize);
    return connectionFactory;
}

@Bean
@ConditionalOnProperty(name = "enable.userconnection", havingValue = "true")
public UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter() throws Exception {
    UserCredentialsConnectionFactoryAdapter connectionFactoryAdapter = new UserCredentialsConnectionFactoryAdapter();
    connectionFactoryAdapter.setUsername(getUsername());
    connectionFactoryAdapter.setPassword(getPassword());
    connectionFactoryAdapter.setTargetConnectionFactory(
        messagingJMSService().getConnectionFactory(getName()));
    return connectionFactoryAdapter;
}

注解说明

  • @ConditionalOnProperty(name = "enable.userconnection", havingValue = "false"):仅当配置enable.userconnection=false时,才会创建CachingConnectionFactory Bean
  • @ConditionalOnProperty(name = "enable.userconnection", havingValue = "true"):仅当配置enable.userconnection=true时,才会创建UserCredentialsConnectionFactoryAdapter Bean
  • matchIfMissing = false(可选):确保当该配置属性未定义时,不会创建对应的Bean;若希望属性未配置时默认启用CachingConnectionFactory,可将该值改为true

内容的提问来源于stack exchange,提问作者TechGeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:05:45