When using Spring, is it possible to set a property only if the value passed is not null?
Example:
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."
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>
You can create a Utility class that will act as a Factory class for some.Type
, and wrap the logic there
For Example :
public class TypeFactory {
public static Type craeteType(SomeType param){
Type t = new Type();
if(param!=null)
t.setParam(param);
}
}
and on XML configure the bean creation using this Factory method
<bean id="myBean" class="some.Type"
factory-method="craeteType">
<constructor-arg ref="param"/>
</bean>
This looks like a job for Java-based container configuration. You'll be able to do what you do in your XML config, but with all the power of Java.
I've got it working with following snippet:
<bean name="myBean" class="some.Type">
<property name="abc" value="#{'${some.param}'=='' ? null : '${some.param}'}" />
</bean>