我的标题可能描述性不够或具有误导性,让我解释一下真实的故事。
我有 3 个 kafka 消费者在同一个 Spring Boot 应用程序上运行,监听不同的主题,都有自己的线程。所有 3 个消费者的工作方式完全相同;处理队列并将它们发送到另一个休息服务。唯一的区别是它们将数据发送到不同的休息服务,因此我明确选择正确的 RestClient
来发送数据,如示例中
@Autowired
internal var restClients: Map<String,RestClient>? = null
fun getOSStats(restClientName: String): Response {
val restClient = restClients[restClientName]
return restClient.performRequest(...)
}
我必须将clusterName: String
传递给从消费者开始的所有方法,只是为了选择消费者定义的正确的RestClient
。
我想要实现的是
@Autowired
internal var restClient:RestClient? = null
fun getOSStats(): Response {
return restClient.performRequest(...)
}
注入(inject)正确的 Bean 而不是从映射中显式选择 Bean 的最佳方法是什么?
我使用 Spring 5.x 和 kotlin
最佳答案
如果你想在运行时在客户端之间切换,我相信这样的查找map
实际上是一个很好的解决方案
如果您知道字符串值并且它是为每个使用者定义的,则只需使用 Qualifier
Spring 注释来指定应将服务接口(interface)的哪个实现 Autowiring 到您的使用者
@Bean("client1Client")
// Bean creating method
...
// and in the 1st consumer class
@Autowired
@Qualifier("client1Client")
internal var restClient:RestClient
关于java - 如何在 Spring 运行时注入(inject)正确的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57324992/