Spring bean depends on conditional bean

I want a spring bean to be created after another bean . So I just use the @DependsOn annotation.

The point is this: this other bean is a conditional bean wearing @ConditionalOnProperty(name = "some.property", havingValue = "true") annotation. Therefore, when the property is false, the bean is not defined (and what we want), and @DependsOn obviously fails. The goal here is to create a second bean anyway, but create it after the first if it was created .

Is there a way to do this without removing @ConditionalOnProperty ? And not playing with the @Order annotation?

thanks for the help

+5
source share
2 answers

How about the following approach:

 interface Something {} public class FirstBean implements Something {} public class SecondBean implements Something{} // maybe empty implementation 

Now the configuration will look like this:

 @Configuration public class MyConfiguration { @Bean(name = "hello") @ConditionalOnProperty(name = "some.property", havingValue = true) public Something helloBean() { return new FirstBean(); } @Bean(name = "hello") @ConditionalOnProperty(name = "some.property", havingValue = false) public Something secondBean() { return new SecondBean(); } @Bean @DependsOn("hello") public MyDependantBean dependantBean() { return new MyDependantBean(); } } 

The idea is to create a "Something" bean anyway (even if it's an empty implementation), so the dependent bean will depend on something anyway.

I have not tried this myself, you know, spring is full of magic, but probably worth a try :)

+1
source

You can use your own condition class:

 public class BeanPresennceCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { FirstBean firstBean = null; try { firstBean = (FirstBean)context.getBeanFactory().getBean("firstBean"); }catch(NoSuchBeanDefinitionException ex) { } return firstBean != null; } } 
0
source

Source: https://habr.com/ru/post/1276033/


All Articles