Ondrej Bozek
Ondrej Bozek

Reputation: 11481

Specify default property value as NULL in Spring

I want to define default property value in Spring XML configuration file. I want this default value to be null.

Something like this:

...
<ctx:property-placeholder location="file://${configuration.location}" 
                          ignore-unresolvable="true" order="2" 
                          properties-ref="defaultConfiguration"/>

<util:properties id="defaultConfiguration">
    <prop key="email.username" >
        <null />
    </prop>  
    <prop key="email.password">
        <null />
    </prop>  
</util:properties>
...

This doesn't work. Is it even possible to define null default values for properties in Spring XML configuration?

Upvotes: 38

Views: 60180

Answers (4)

EpicPandaForce
EpicPandaForce

Reputation: 81539

It appears you can do the following:

@Value("${some.value:null}")
private String someValue;

and

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertySourcesPlaceholderConfigurer.setNullValue("null");
    return propertySourcesPlaceholderConfigurer;
}

Upvotes: 3

Andrei Cojocaru
Andrei Cojocaru

Reputation: 171

have a look at PropertyPlaceholderConfigurer#setNullValue(String)

It states that:

By default, no such null value is defined. This means that there is no way to express null as a property value unless you explictly map a corresponding value

So just define the string "null" to map the null value in your PropertyPlaceholderConfigurer:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="nullValue" value="null"/>
    <property name="location" value="testing.properties"/>
</bean>

Now you can use it in your properties files:

db.connectionCustomizerClass=null
db.idleConnectionTestPeriod=21600

Upvotes: 4

Anton Kirillov
Anton Kirillov

Reputation: 1316

It is better to use Spring EL in such way

<property name="password" value="${email.password:#{null}}"/>

it checks whether email.password is specified and sets it to null (not "null" String) otherwise

Upvotes: 109

YoK
YoK

Reputation: 1636

You can try use Spring EL.

<prop key="email.username">#{null}</prop>

Upvotes: 4

Related Questions