1. 通過set方法配置Bean屬性
在XML文件中配置bean,通過property屬性設置值時,要注意property的name的值和類成員屬性的set方法名(除掉set的部分)一一對應。
Person類
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
XML文件
<bean id="xiaohong" class="main.Person">
<property name="name" value="xiaohong"></property>
<property name="age" value="99"></property>
</bean>
如果將Person類方法改爲如下,就會出錯
public void setName1(String name) {
this.name = name;
}
public void setAge1(int age) {
this.age = age;
}
報錯信息(截取第一行):
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘xiaohong’ defined in class path resource [spring-config.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘name’ of bean class [main.Person]: Bean property ‘name’ is not writable or has an invalid setter method. Did you mean ‘name1’?
此時需將XML文件中name值對應修改
<bean id="xiaohong" class="main.Person">
<property name="name1" value="xiaohong"></property>
<property name="age1" value="99"></property>
</bean>
當然,日常代碼中應該都會默認用類屬性名填充XML中property的name值;這裏只是做一個理解方面的介紹,避免萬一出錯不知道原因出在哪。