使用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