Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

java - Intentionally setting a Spring bean to null

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.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm pretty sure that Spring won't allow you to associate null with a bean id or alias. You can handle this by setting properties to null.

Here's how you did this in Spring 2.5

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

In Spring 3.0, you should also be able to use the Spring expression language (SpEL); e.g.

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

or any SpEL expression that evaluates to null.

And if you are using a placeholder configurator you could possibly even do this:

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

where some.prop could be defined in a property file as:

some.prop=null

or

some.prop=some.bean.id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...