hevi
hevi

Reputation: 2716

How to inject correct bean on runtime on Spring

My title may not be descriptive enough or misleading let me explain the real story.

I've 3 kafka consumers running on the same spring boot app listening different topics, all have their own threads. All of the 3 consumers work exactly the same; process the queue and send them to another rest service. The only difference is that they send the data to different rest services thus I explicitly select the correct RestClient to send the data as in the example

    @Autowired
    internal var restClients: Map<String,RestClient>? = null

    fun getOSStats(restClientName: String): Response {
        val restClient = restClients[restClientName]
        return restClient.performRequest(...)
    }

I have to pass the clusterName: String to all the methods starting from the consumer just to pick the correct RestClient which is defined by the consumer.

What I want to achieve is

    @Autowired
    internal var restClient:RestClient? = null

    fun getOSStats(): Response {
        return restClient.performRequest(...)
    }

What is the best way to inject the correct bean instead of explicitly select the bean from a map?

I use Spring 5.x and kotlin

Upvotes: 1

Views: 78

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13571

If you want to switch between clients in runtime I believe that such lookup map is actually good solution

If you know string value and it's defined for every consumer just use the Qualifier Spring annotation to specify which implementation of the service interface should be autowired to your consumer

 @Bean("client1Client")
 // Bean creating method

 ...

 // and in the 1st consumer class
 @Autowired
 @Qualifier("client1Client")
 internal var restClient:RestClient

Upvotes: 1

Related Questions