我正在尝试使用 Spring,我正在关注这本书:Spring: A developer's notebook。我收到此错误:
“Bean属性‘storeName’不可写或setter方法无效。setter的参数类型与getter的返回类型是否匹配?”
..我很迷茫。
我有一个实现 RentABike
的 ArrayListRentABike
类:
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 注入(inject),但没有为属性 storeName
定义 setter。为 storeName
添加 setter/getter 或使用构造函数注入(inject)。
由于您已经定义了一个将 storeName
作为输入的构造函数,我想说将您的 RentABike-context.xml
更改为以下内容:
<bean id="rentaBike" class="ArrayListRentABike">
<constructor-arg index="0"><value>Bruce's Bikes</value></constructor-arg>
</bean>
关于Spring:Bean属性不可写或具有无效的setter方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3930844/