Spring - 仅当值不为空时才设置属性

2022-09-01 15:32:12

使用 Spring 时,是否可以仅在传递的值不为 null 时才设置属性?

例:

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

我正在寻找的行为是:

some.Type myBean = new some.Type();
if (${some.param} != null) myBean.setAbc(${some.param});

我需要它的原因是因为有一个默认值,我不想用.而且我正在创建的Bean不在我的源代码控制之下 - 所以我无法更改其行为。(另外,出于这个目的,可能是一个基元,所以我无论如何都不能用空值来设置它。abcnullabc

编辑:
根据答案,我认为我的问题需要澄清。

我有需要实例化并传递给我使用的第三方的bean。这种豆子具有许多各种类型的属性(目前有12个)(,,等)。
每个属性都有一个默认值 - 我不知道它是什么,除非它成为一个问题,否则宁愿不需要知道。我正在寻找的是一种来自Spring能力的通用解决方案 - 目前我唯一的解决方案是基于反射的。intbooleanString

配置

<bean id="myBean" class="some.TypeWrapper">
   <property name="properties">
     <map>
         <entry key="abc" value="${some.value}"/>
         <entry key="xyz" value="${some.other.value}"/>
         ...
      </map>
   </property>
</bean>

法典

public class TypeWrapper
{
    private Type innerBean;

    public TypeWrapper()
    {
        this.innerBean = new Type();
    }

    public void setProperties(Map<String,String> properties)
    {
        if (properties != null)
        {
            for (Entry<String, Object> entry : properties.entrySet())
            {
                String propertyName = entry.getKey();
                Object propertyValue = entry.getValue();

                setValue(propertyName, propertyValue);
            }
        }
    }

    private void setValue(String propertyName, Object propertyValue)
    {
        if (propertyValue != null)
        {
           Method method = getSetter(propertyName);
           Object value = convertToValue(propertyValue, method.getParameterTypes()[0]);
           method.invoke(innerBean, value);
        }
    }

    private Method getSetter(String propertyName)
    {
      // Assume a valid bean, add a "set" at the beginning and toUpper the 1st character.
      // Scan the list of methods for a method with the same name, assume it is a "valid setter" (i.e. single argument)
      ... 
    }

    private Object convertToValue(String valueAsString, Class type)
    {
        // Check the type for all supported types and convert accordingly
        if (type.equals(Integer.TYPE))
        {
          ...
        }
        else if (type.equals(Integer.TYPE))
        {
          ...
        }
        ...
    }
}

真正的“困难”在于实现所有可能的值类型。我一生中不止一次这样做过 - 所以为我需要的所有可能类型(主要是基元和一些枚举)实现它不是一个大问题 - 但我希望存在一个更智能的解决方案。convertToValue


答案 1

您可以同时使用占位符机制的占位符和默认值,如下所示:SpEL

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

答案 2

为了解决您的问题,您必须使用SEL(弹簧表达式语言)。通过此功能(在SPring 3.0中添加),您可以像其他动态语言一样编写您的条件。对于您的上下文,答案是:

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

有关详细信息,请参阅(本教程说明在上下文文件中使用 SEL 的内容):http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html


推荐