qmained
qmained

Reputation: 3

Conditional bean result based on another bean

I have two service beans implementing the same interface, and one of them is primary, but it should be instantiated only if other service bean returns true. So if the result of executing a boolean method of this check bean is true, then the primary service bean is instantiated, else it's not.

I want to make it using a Conditional annotation. I made a class that implements Conditional, but I cannot autowire my check bean in it. I think the approach with using Conditional annotation would make my code cleaner. I found another solution in which I created new Configuration annotated class with my check bean autowired, then I created a Bean annotated method that returns one of two service beans based on a return value from my check bean. This solution works, but it seems a bad practise because I cannot autowire dependencies in service beans that I create using "new" in @Bean method. So my question is how can I make it using Conditional, or is there a better solutinon for that.

Upvotes: 0

Views: 83

Answers (1)

Rob Spoor
Rob Spoor

Reputation: 9100

If you implement Condition or extend SpringBootCondition, the first argument of the method to implement (matches and getMatchOutcome respectively) is the ConditionContext. This gives you access to the bean factory, which you can use to lookup your primary bean.

Upvotes: 0

Related Questions