Intentionally setting a Spring bean to null

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

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" />

Tags:

Java

Spring