我正在使用新的Spring Boot2.0M7,并且我正在尝试定义一些条件逻辑来根据活动配置文件加载不同的bean。
我有这个(有效的) bean配置。它为除test和activemq for test之外的所有环境定义了一个基于sqs的连接工厂。
@Configuration
@EnableJms
public class QueueConfig {
private static Logger LOG = LoggerFactory.getLogger(QueueConfig.class);
@Profile({"!test"})
@Bean
public ConnectionFactory sqsConnectionFactory() {
LOG.info("using sqs");
return new SQSConnectionFactory(new ProviderConfiguration(), AmazonSQSClientBuilder.standard()
.withRegion(Regions.EU_WEST_1)
.withCredentials(new DefaultAWSCredentialsProviderChain())
);
}
@Profile({"test"})
@Bean
public ConnectionFactory activeMqConnectionFactory() {
LOG.info("using activemq");
return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
}
@Bean
public JmsTemplate defaultJmsTemplate(ConnectionFactory connectionFactory) {
return new JmsTemplate(connectionFactory);
}
@Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setDestinationResolver(new DynamicDestinationResolver());
factory.setConcurrency("3-10");
return factory;
}
}这适用于单个配置文件。我可以在我的测试中看到(用@ActiveProfiles("test")注释的)测试概要文件是活动的,并且加载了正确的bean (日志消息)。
但是,在sqsConnectionFactory上将@Profile({"!test"})更改为@Profile({"!test","!dev}),在activeMqConnectionFactory上将@Profile({"test"})更改为@Profile({"test","dev})会造成破坏。
我得到了一个未解决的bean异常,因为它现在有两个实例,而不是1个。我可以在我的日志中看到测试配置文件仍然是活动的,尽管如此,它仍然很高兴地加载了sqs和activemq实现,尽管它不应该加载。
在spring boot 2.x中,@Profile的逻辑有什么变化吗?如果是这样,我如何定义在dev或test profile处于活动状态时使用activemq实现,而在其他情况下使用sqs?
如果不是,我在这里做错了什么?
发布于 2018-01-08 20:36:25
有很多方法可以解决这个问题。这里有一个:创建另一个配置文件sqs。使用它来启用或禁用bean。
@Profile({"sqs"})
@Bean
public ConnectionFactory sqsConnectionFactory() { ... }
@Profile({"!sqs"})
@Bean
public ConnectionFactory activeMqConnectionFactory() { ... }然后在配置文件中声明您的配置文件使用此配置文件,或者不使用此配置文件:
---
spring.profiles: dev
...
---
spring.profiles: test
...
---
spring.profiles: prod
spring.profiles.include:
- sqs发布于 2018-01-08 23:50:11
@Profile({"!test","!dev}) -这里你在!dev之后遗漏了一个",但是,如果这只是这里的一个拼写错误,请尝试以下(对我有效)
@Profile(value={"!test", "!dev"})顺便说一句,我个人更喜欢每个类有一个配置@Bean,在这种情况下,你基本上是用@Profile注释整个类,对我来说,它很容易阅读
https://stackoverflow.com/questions/48149805
复制相似问题