春季豆取决于条件豆 [英] Spring bean depends on a conditional bean

查看:95
本文介绍了春季豆取决于条件豆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在另一个豆之后实例化一个弹簧豆.所以我只使用@DependsOn批注.

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

问题是:另一个bean是有条件的bean @ConditionalOnProperty(name = "some.property", havingValue = "true")注释. 因此,当该属性为false时,就不会实例化bean(这就是我们想要的),并且@DependsOn显然会失败.这里的目标是:仍然创建第二个bean,但是在第一个如果已创建之后创建它.

The thing is : this other bean is a conditional bean wearing the @ConditionalOnProperty(name = "some.property", havingValue = "true") annotation. So when the property is false then the bean is not instanciated (and that's what we want), and the @DependsOn obviously fails. The goal here is : create the second bean anyway, but create it after the first one if it was created.

是否可以在不删除@ConditionalOnProperty的情况下做到这一点?并且不使用@Order批注吗?

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

谢谢您的帮助

推荐答案

以下方法如何:

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.

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:)

这篇关于春季豆取决于条件豆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆