Spring - set a property only if the value is not null Spring - set a property only if the value is not null spring spring

Spring - set a property only if the value is not null


You can use SpEL and placeholder and default value for placeholder mechanisms together as following:

<bean name="myBean" class="some.Type">    <property name="abc" value="${some.param:#{null}}"/></bean>


For solve your problem, you have to use SEL(Spring Expression Language).By this feature (added in SPring 3.0) you can such as other dynamic language writing your condition. For your context, answer is:

<bean name="myBean" class="some.Type">   <property name="abc" value="#(if(${some.param} != null) ${some.param})"/></bean>

for more information see(this tutorial says what use SEL in context file):http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html


You can use default value concept in property configurer in Spring framework as following:

<bean name="myBean" class="some.Type">   <property name="abc" value="${some.param : your-default-value}"/></bean>

you can set default value by this approach. By this context config if some.param key exist so its value set in abc property and if don't exist your-default-value set in abc property.

Note: Another benefit of this approah is:"In POJO programming model better approzh is member of class don't have any default value,and default value injected from out of class."