0

I am trying to do conditional auto-wiring in Spring using annotation-based configuration. I have 2 different beans both implementing the same interface. I would like to do something like

if(some condition) choose bean 1 to autowire else choose bean 2 to autowire

Is there a way to do this? I noticed the @Primary and @Qualifier annotations, but they will only choose one bean or the other to autowire and not based on some condition. Thanks.

Vikram
  • 23
  • 3

1 Answers1

0

Autowiring injects a bean into the target bean only once, when the target object is being initialized. Afterwards it remain unchanged.

Consider other approaches. For instance, inject both beans and implement a method that selects one of these beans depending on your conditions.

mentallurg
  • 4,967
  • 5
  • 28
  • 36
  • Thanks a lot @mentallurg. That looks to be working for me. I have made one bean primary and put the conditional logic in a separate method. – Vikram Oct 05 '19 at 20:31