ritratt
ritratt

Reputation: 1858

How to pick a bean based on a condition?

I have two implementations of an interface

@Component
public ClassA implements SomeInterface {
}
@Component
public classB implements SomeInterface {
}

And then a consumer that needs an implementation of the class depending on some condition. How do I pick a particular bean?

@Component
public class Consumer {
  @PickTheRightBean(if(condition) then pick SomeClassA else pick SomeClassB) \\ how do I do this?
  private final SomeInterface myBean;
}

I tried @Conditional annotation, but it still ends up picking the wrong bean.

Upvotes: 1

Views: 918

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19193

The only feasible way to achieve what you want IMO, is to get rid of the annotation @Component on Consumer class so that it becomes

public class Consumer {
  
  private final SomeInterface myBean;
}

and you register it using your custom logic in a configuration class

 @Configuration
 public class MyConfiguration{

 @Bean
 public Consumer consumer(ClassA classA, ClassB classB) {

   Consumer consumer = new Consumer();
   if (your condition here){
        consumer.setMyBean(classA);
   } else {
        consumer.setMyBean(classB);
   }
   return consumer;
 }

}

Upvotes: 1

Related Questions