我正在尝试 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_马耳他
您正在使用 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>
由于传递给构造函数的参数将初始化
storeName
,因此您可以使用 constructor-arg
元素来设置 storeName
。
<bean id="rentaBike" class="ArrayListRentABike">
<constructor-arg value="Bruce's Bikes"/>
</bean>
constructor-arg
元素允许将参数传递给 Spring bean 的构造函数(惊喜,惊喜)。
出现此错误是因为未为值解决方案定义storeName:
<bean id="rentaBike" class="ArrayListRentABike">
<property name="storeName"><value>"Bruce's Bikes"</value></property>
</bean>
对于这种类型的错误,有时还需要检查字段的访问修饰符,如果是默认的,spring 可能会抛出错误。 setter 的访问修饰符应该是 public,以便 spring 可以使用它来设置属性