在我们项目的一个公共(public)库中,我需要根据服务正在使用的接口(interface)来区分接口(interface)的两种实现。
我通过构造函数注入(inject)来注入(inject)此接口(interface),并且需要了解如何根据 application.yml 中的属性值确定使用哪种实现。
我研究了 @Qualifier 注释,但这似乎确实需要 xml 模式中的属性。我们没有这样的东西。
在代码的一部分中,我们以这种方式读出 KafkaListener 的属性
@KafkaListener(topics = "#{PathToProperties.getPrefix()}#OurBusinessProperties.getRelevantProperties()}"
我可以在 Spring 中使用相同的语法吗?
最佳答案
In one of our common libraries for our project I need to make an distinction between two implementations of an interface based on what Service is using it.
您可以使用配置文件来执行此操作。
假设您有两个配置文件:生产和测试。
然后您可以注释要在生产中使用的实现,如下所示:
@Profile("production")
@Component
class ProductionImplementation implements MyService {
}
并在另一个组件上设置不同的配置文件:
@Profile("test")
@Component
class TestImplementation implements MyService {
}
然后使用以下参数启动您的 spring-boot 应用程序:
-Dspring.profiles.active=production
或者,您可以使用环境变量选择配置文件:
SPRING_PROFILES_ACTIVE = production
还有一个选择是创建一个工厂,该工厂将根据某些环境配置创建不同的实例:
@Bean
public MyService myService() {
if (condition) return FirstImplementation();
return SecondImplementation();
}
关于java - 根据 application.yml 中的属性使用 Spring Boot 进行注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368915/