java 如何了解运行时是否存在 bean?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14723984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:09:30  来源:igfitidea点击:

How can I understand whether a bean exists in runtime?

javaspringjavabeans

提问by Mary Ryllo

For example, I have a class

例如,我有一个类

public class Car{
     private Motor motor;

     public void setMotor(Motor motor){
          this.motor = motor;
     }   
}

My bean looks like

我的豆子看起来像

<bean id="car" class="Car">
    <property name="motor" ref="${motorProvider.getAvailableMotor()}"/>
</bean>

This method: motorProvider.getAvailableMotor()returns a bean name(string), of which motor I should use.

这个方法: motorProvider.getAvailableMotor()返回一个bean名称(字符串),我应该使用哪个电机。

But there can be a situation when such bean(with such name) is not created. How can I check it?

但是可能存在未创建此类 bean(具有此类名称)的情况。我该如何检查?

回答by Aaron Digulla

There are several patterns how to do this. Here is one I often use:

有几种模式可以做到这一点。这是我经常使用的一种:

public class Car{
     private Motor motor;

     @Autowired
     private ApplicationContext applicationContext;

     @PostConstruct
     public void init() {
        try {
            motor = applicationContext.getBean( Motor.class );
        } catch( NoSuchBeanDefinitionException e ) {
            motor = new DefaultMotor();
        }
     }
}

Note you could also call applicationContext.containsBeanDefinition(name)but that would search your context twice (once in containsBeanDefinition()and then second time when you call getBean()) so catching the exception is usually faster.

请注意,您也可以调用,applicationContext.containsBeanDefinition(name)但这会搜索您的上下文两次(一次containsBeanDefinition(),然后在您调用时第二次getBean()),因此捕获异常通常会更快。

Since we catch a specific exception that says "bean doesn't exist", using if/elsehas almost no advantage anymore.

由于我们捕获了一个说“bean 不存在”的特定异常,因此使用if/else几乎没有任何优势了。

回答by user1121883

SPeL; something like:

标语;就像是:

<property name="motor" value="#(if(${motorProvider} != null) ${motorProvider.getAvailableMotor()})"/>

I think it was discussed also here: Spring - set a property only if the value is not null. As they said before for more information see: http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html

我认为这里也讨论过:Spring - set a property only if the value is not null。正如他们之前所说的更多信息,请参见:http: //static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html