如何基于配置属性条件化创建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时,才会创建CachingConnectionFactoryBean@ConditionalOnProperty(name = "enable.userconnection", havingValue = "true"):仅当配置enable.userconnection=true时,才会创建UserCredentialsConnectionFactoryAdapterBeanmatchIfMissing = false(可选):确保当该配置属性未定义时,不会创建对应的Bean;若希望属性未配置时默认启用CachingConnectionFactory,可将该值改为true
内容的提问来源于stack exchange,提问作者TechGeek
相关产品推荐
相关产品推荐

