我正在尝试使用Spring,我正在阅读这本书:Spring:开发人员的笔记本。我收到了这个错误:
"Bean property 'storeName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?"
..我很失落。
我有一个ArrayListRentABike
类来实现RentABike
:
import java.util.*;
public class ArrayListRentABike implements RentABike {
private String storeName;
final List bikes = new ArrayList( );
public ArrayListRentABike( ) { initBikes( ); }
public ArrayListRentABike(String storeName) {
this.storeName = storeName;
initBikes( );
}
public void initBikes( ) {
bikes.add(new Bike("Shimano", "Roadmaster", 20, "11111", 15, "Fair"));
bikes.add(new Bike("Cannondale", "F2000 XTR", 18, "22222", 12, "Excellent"));
bikes.add(new Bike("Trek", "6000", 19, "33333", 12.4, "Fair"));
}
public String toString( ) { return "RentABike: " + storeName; }
public List getBikes( ) { return bikes; }
public Bike getBike(String serialNo) {
Iterator iter = bikes.iterator( );
while(iter.hasNext( )) {
Bike bike = (Bike)iter.next( );
if(serialNo.equals(bike.getSerialNo( ))) return bike;
}
return null;
}
}
我的RentABike-context.xml
就是这样:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="rentaBike" class="ArrayListRentABike">
<property name="storeName"><value>"Bruce's Bikes"</value></property>
</bean>
<bean id="commandLineView" class="CommandLineView">
<property name="rentaBike"><ref bean="rentaBike"/></property>
</bean>
</beans>
有什么想法吗? 非常感谢! Krt_Malta
答案 0 :(得分:12)
您正在使用setter注入,但没有为属性storeName
定义setter。为storeName
添加setter / getter或使用构造函数注入。
由于您已经定义了一个以storeName
作为输入的构造函数,因此我要将您的RentABike-context.xml
更改为以下内容:
<bean id="rentaBike" class="ArrayListRentABike">
<constructor-arg index="0"><value>Bruce's Bikes</value></constructor-arg>
</bean>
答案 1 :(得分:10)
由于传递给构造函数的参数将初始化storeName
,因此您可以使用constructor-arg
元素设置storeName
。
<bean id="rentaBike" class="ArrayListRentABike">
<constructor-arg value="Bruce's Bikes"/>
</bean>
constructor-arg
元素允许将参数传递给spring bean的构造函数(惊讶,惊讶)。
答案 2 :(得分:0)
发生此错误是因为没有为值解决方案定义的storeName位于:
<bean id="rentaBike" class="ArrayListRentABike">
<property name="storeName"><value>"Bruce's Bikes"</value></property>
</bean>