将Spring bean设置为null

问题描述

factory-bean/ factory-method不适用于null,但自定义factorybean实现的效果很好:

public class Nullfactorybean implements factorybean<Void> {

    public Void getobject() throws Exception {
        return null;
    }

    public Class<? extends Void> getobjectType() {
        return null;
    }

    public boolean isSingleton() {
        return true;
    }
}
<bean id="jmsConnectionFactory" class = "com.sample.Nullfactorybean" />

Spring不允许你将其null与bean id或别名关联。你可以通过将属性设置为null来处理此问题。

这是你在Spring 2.5中的操作方式

<bean class="ExampleBean">
    <property name="email"><null/></property>
</bean>

在Spring 3.0中,你还应该能够使用Spring表达式语言(SpEL) ; 例如

<bean class="ExampleBean">
    <property name="email" value="#{ null }"/>
</bean>

或任何计算为的SpEL表达式null。

如果你使用的是占位符配置器,甚至可以这样做:

<bean class="ExampleBean">
    <property name="email" value="#{ ${some.prop} }`"/>
</bean>

some.prop属性文件中可以将以下位置定义为:

some.prop=null

要么

some.prop=some.bean.id

解决方法

我正在使用Spring将JMS连接工厂注入到我的Java应用程序中。由于仅在生产环境中才需要该工厂,但是在开发过程中却不需要,因此我将Bean定义放入单独的XML中,并将其包含在主applicationContext.xml中。在生产环境中,此额外文件包含常规bean定义。在我的本地开发环境中,我希望此bean为null。当Spring遇到一个未知的引用ID时,试图完全完全删除Bean定义显然会导致错误。

因此,我尝试创建仅返回null的工厂bean。如果我这样做,Spring(2.5.x)会抱怨工厂返回了null,尽管基于FactoryBean接口的Spring API文档,我希望它可以正常工作(请参见Spring API doc)。

XML看起来像这样:

<bean id="jmsConnectionFactoryFactory" class="de.airlinesim.jms.NullJmsConnectionFactoryFactory" />

<bean id="jmsConnectionFactory" factory-bean="jmsConnectionFactoryFactory" factory-method="getObject"/>

这样做的“正确”方法是什么?