简体   繁体   English

@ConditionalOnBean 不适用于手动注册的 bean

[英]@ConditionalOnBean does not work with manually registered bean

I have such an issue.我有这样的问题。 On the basis of the database configuration I need to create appropriate beans that will handle whole process.在数据库配置的基础上,我需要创建适当的 bean 来处理整个过程。 I've figured out that I will try do it in the following way.我发现我会尝试按照以下方式进行。 First, create the marker bean on the basis of db config .首先,在 db config 的基础上创建标记 bean。

@Configuration
class Dbconfig {
  @Autowired DbRepo dbRepo;
  @Autowired GenericApplicationContext applicationContext;
  @PostConstruct
  public void init(){
    Config config = dbRepo.findConfiguration();
    if(config.value.equals("test")){
      applicationContext.registerBean("testBean", TestBean.class, TestBean::new);
    }else{ //other steps
  }
}

Then, on the basis of this marker bean I will create the proper ones, like:然后,在这个标记 bean 的基础上,我将创建适当的标记 bean,例如:

@Configuration
@ConditionalOnBean(name = "testBean")
@AutoConfigureAfter(value = Dbconfig.class)
public class ObjConfig{
//creating proper @Beans
  }

But, unfortunately, it does not work.但是,不幸的是,它不起作用。 Don't know why spring does not seem to see this “testBean”.不知道为什么spring好像没有看到这个“testBean”。 Nevertheless, I have debugged it and I can see this bean exists in BeanFactory of the Application Context.尽管如此,我已经调试了它,我可以看到这个 bean 存在于应用程序上下文的 BeanFactory 中。 It also works smoothly with the @DependsOn annotation, then spring can see this bean.配合@DependsOn注解也很顺利,然后spring就可以看到这个bean了。 I will appreciate any help or suggestions how to resolve the problem in other way.对于如何以其他方式解决问题的任何帮助或建议,我将不胜感激。

@AutoConfigureAfter will only work on an auto-configuration class and not for manually configured beans. @AutoConfigureAfter仅适用于自动配置类,不适用于手动配置的 bean。 If you were wiring testBean as a Autowired bean your code will work.如果您将 testBean 作为Autowired bean 连接,您的代码将起作用。 You may try @ConditionalOnExpression to inject bean based on an SpEL expression.您可以尝试@ConditionalOnExpression基于SpEL表达式注入 bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM