我正在學習Spring並編寫一個簡單的程序來將屬性注入到POJO中。下面是主類 -依賴性注入時的彈性錯誤
public class test {
public static void main (String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
MySpring sm = (MySpring)context.getBean("myspring");
System.out.println(sm);
}
}
的POJO如下 -
public class MySpring {
public String count;
void setcount(String val){
this.count = val;
}
String getcount(){
return count;
}
}
而且配置文件是低於 -
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="myspring" class="MySpring" >
<property name="count" value="PowerShell" />
</bean>
</beans>
但是我收到以下錯誤,當我運行test.java類 -
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myspring' defined in class path resource [Beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'count' of bean class [MySpring]: Bean property 'count' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at
.....
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.main(test.java:7)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'count' of bean class [MySpring]: Bean property 'count' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1064)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924)
我知道這是一個常見的錯誤,但我無法找到根本原因,因爲一切似乎都很好。任何關於什麼可能是問題的指針是高度讚賞。
對不起,我的無知,但如果你看到我的POJO MySpring,我確實有一個setter的count屬性..void setcount(String val){this.count = val; } – user496934
是否有任何需要遵守的具體慣例。 – user496934
是的setter需要是公共的,約定是setCount(),第一個字符應該在CAP中。最好的是如果你使用IDE爲你創建setter。 – Anshu