1

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.

ritratt
  • 1,703
  • 4
  • 25
  • 45

1 Answers1

1

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;
 }

}
Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47