Spring bean depends on a conditional bean

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

    Instead of using @DependsO you can use @AutoConfigureAfter()which will allow the second bean to be created even if the first bean was not created, but still keep the order.

    @Configuration
    public class FirstConfiguration {
    
      @Bean(name = "firstBean")
      @ConditionalOnProperty(name = "some.property", havingValue = true) 
      public FirstBean firstBean() {
         return new FirstBean();
      }
    }
    
    @Configuration
    @AutoConfigureAfter(name = {"firstBean"})
    public class SecondConfiguration {
    
      @Bean
      public SecondBean secondBean() {
           return new SecondBean();
      }
    }
    

提交回复
热议问题