Spring - 仅当值不为空时才设置属性
使用 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不在我的源代码控制之下 - 所以我无法更改其行为。(另外,出于这个目的,可能是一个基元,所以我无论如何都不能用空值来设置它。abc
null
abc
编辑:
根据答案,我认为我的问题需要澄清。
我有需要实例化并传递给我使用的第三方的bean。这种豆子具有许多各种类型的属性(目前有12个)(,,等)。
每个属性都有一个默认值 - 我不知道它是什么,除非它成为一个问题,否则宁愿不需要知道。我正在寻找的是一种来自Spring能力的通用解决方案 - 目前我唯一的解决方案是基于反射的。int
boolean
String
配置
<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