Spring:Bean 属性不可写或具有无效的 setter 方法

问题描述 投票:0回答:4

我正在尝试 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_马耳他

spring javabeans
4个回答
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>

10
投票

由于传递给构造函数的参数将初始化

storeName
,因此您可以使用
constructor-arg
元素来设置
storeName

<bean id="rentaBike" class="ArrayListRentABike">
    <constructor-arg  value="Bruce's Bikes"/>
</bean>

constructor-arg
元素允许将参数传递给 Spring bean 的构造函数(惊喜,惊喜)。


0
投票

出现此错误是因为未为值解决方案定义storeName:

<bean id="rentaBike" class="ArrayListRentABike">
    <property name="storeName"><value>"Bruce's Bikes"</value></property>
</bean>

0
投票

对于这种类型的错误,有时还需要检查字段的访问修饰符,如果是默认的,spring 可能会抛出错误。 setter 的访问修饰符应该是 public,以便 spring 可以使用它来设置属性

© www.soinside.com 2019 - 2024. All rights reserved.