问题描述
我正在使用Spring将JMS连接工厂注入我的Java应用程序。由于这个工厂只在生产环境中需要,而不是在我开发的时候,我把bean定义放到一个单独的XML中,我将其包含在我的主applicationContext.xml中。在生产环境中,此额外文件包含常规bean定义。在我的本地开发环境中,我希望这个bean为null。当Spring遇到它不知道的引用ID时,试图简单地删除bean定义,显然会导致错误。
I'm using Spring to inject JMS connection factory into my Java application. Since this factory is only required within the production environment, not while I'm developing though, I put the bean definition into a separate XML which I include into my main applicationContext.xml. In production environments this extra file contains the regular bean definition. In my local dev environment I'd like this bean to be null. Trying to simply remove the bean definition all-toghether obviously caused an error when Spring came across a reference ID it didn't know.
所以我尝试创建一个只返回null的工厂bean。如果我这样做,Spring(2.5.x)抱怨工厂返回null虽然基于FactoryBean接口的Spring API文档,我希望这可以工作(参见)。
So I tried creating a factory bean that would simply return null. If I do this, Spring (2.5.x) complains that the factory returned null although based on the Spring API doc of the FactoryBean interface I expected this to work (see Spring API doc).
XML看起来像这样:
The XML looks something like this:
<bean id="jmsConnectionFactoryFactory" class="de.airlinesim.jms.NullJmsConnectionFactoryFactory" />
<bean id="jmsConnectionFactory" factory-bean="jmsConnectionFactoryFactory" factory-method="getObject"/>
这样做的正确方法是什么?
What would be the "correct" way of doing this?
推荐答案
factory-bean
/ factory-method
不使用 null
,但自定义 FactoryBean
实现正常工作:
factory-bean
/factory-method
doesn't work with null
, but a custom FactoryBean
implementation works fine:
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 bean设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!