春豆依赖于有条件的豆子

2022-09-02 04:37:22

我想要一个春豆在另一个豆子之后被实例化。所以我只是使用注释。@DependsOn

问题是:这个另一个豆子是一个戴着注释的条件豆。因此,当属性为假时,豆子没有被实例化(这就是我们想要的),并且显然失败了。这里的目标是:无论如何都要创建第二个bean,但如果它是在创建的第一个bean之后创建它@ConditionalOnProperty(name = "some.property", havingValue = "true")@DependsOn

有没有办法在不删除的情况下做到这一点?而且不用玩注释?@ConditionalOnProperty@Order

感谢您的帮助


答案 1

以下方法怎么样:

interface Something {}

public class FirstBean implements Something {}

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

现在配置如下:

@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();
  }
}

这个想法是无论如何都要创建“Something”bean(即使它是一个空的实现),这样依赖的bean在任何情况下都会依赖于Something。

我自己没有尝试过,你知道,春天充满了魔力,但可能值得一试:)


答案 2

而不是使用,你可以使用这将允许创建第二个bean,即使第一个Bean没有被创建,但仍然保持顺序。@DependsOn@AutoConfigureAfter()

@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();
  }
}

推荐