Spring bean depends on a conditional bean

后端 未结 4 755
小鲜肉
小鲜肉 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:12

    How about the following approach:

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

    Now the configuration goes 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 the "Something" bean anyway (even if its an empty implementation), so that the dependant bean will depend on Something in any case.

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

提交回复
热议问题