Spring bean depends on a conditional bean

后端 未结 4 776
小鲜肉
小鲜肉 2021-02-19 02:58

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

The thing is : this other bean is a

4条回答
  •  鱼传尺愫
    2021-02-19 03:23

    Could you create two definitions for the dependent bean, to cater for the two cases where the other bean is or isn't there?

    E.g.:

    @Bean(name = "myDependentBean")
    @DependsOn("otherBean")
    @ConditionalOnProperty(name = "some.property", havingValue = true) 
    public DependentBean myDependentBean() {
        return new DependentBean();
    }
    
    @Bean(name = "myDependentBean")
    @ConditionalOnProperty(name = "some.property", havingValue = false, matchIfMissing = true) 
    public DependentBean myDependentBean_fallback() {
        return new DependentBean();
    }
    

    (This is the approach I've just taken today to solve a similar problem!)

    Then Spring would use the first definition if some.property is true, and so instantiate myDependentBean after otherBean. If some.property is missing or false, Spring will use the second definition, and so not care about otherBean.

    Alternatively, you could probably use @ConditionalOnBean/@ConditionalOnMissingBean on these, instead of @ConditionalOnProperty (though I've not tried this).

提交回复
热议问题