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

前端 未结 6 1683
星月不相逢
星月不相逢 2020-12-14 01:28

When using Spring, is it possible to set a property only if the value passed is not null?

Example:


          


        
相关标签:
6条回答
  • 2020-12-14 02:04

    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

    0 讨论(0)
  • 2020-12-14 02:06

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

    0 讨论(0)
  • 2020-12-14 02:14

    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>
    
    0 讨论(0)
  • 2020-12-14 02:14

    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>
    
    0 讨论(0)
  • 2020-12-14 02:16

    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.

    0 讨论(0)
  • 2020-12-14 02:31

    I've got it working with following snippet:

    <bean name="myBean" class="some.Type">
        <property name="abc" value="#{'${some.param}'=='' ? null : '${some.param}'}" />
    </bean>
    
    0 讨论(0)
提交回复
热议问题