使用Spring时,是否可以在传递的值不为null时设置属性?Spring - 只有当值不为空时才设置属性
例子:
<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});
我之所以需要这个是因为abc
有,我不想覆盖默认值一个null
。 而我创建的Bean不在我的源代码控制之下 - 所以我无法改变它的行为。 (另外,abc
为此目的可能是一个原始的,所以我不能用空设置也无妨
编辑:
根据我觉得我的问题需要澄清的答案
我。我需要实例化并传递给第三方,这个bean有很多不同类型的属性(当前有12个)(int
,boolean
,String
等)
每个属性都有一个默认值 - 我不知道它是什么,并且宁愿不需要知道,除非它成为问题。 我在寻找的是来自Spring能力的通用解决方案 - 目前我拥有的唯一解决方案是基于反射的解决方案。
配置
<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
。我已经在我的生活中不止一次地完成了这个任务 - 所以在我需要的所有可能的类型(主要是原语和几个枚举)上实现它并不是一个大问题 - 但我希望存在一个更智能的解决方案。
谢谢你的提示 - 这可能是将来会有帮助,但在我的情况下,我无法使用它 - 正如我所说,这个bean不在我的源代码控制中 - 所以我不知道它的默认值是什么(并且不想知道)。我希望得到以下几行: '' –
RonK
2012-02-19 09:37:33