“java.util.ArrayList <java.lang.string>”类型的属性不能通过“List”注入

时间:2016-07-11 08:10:36

标签: xml spring intellij-idea

我使用intelliJ IDEA 16.1版本来练习Spring框架。

学生班

package com.tistory.johnmarc;
import java.util.ArrayList;

public class Student {

private String name;
private int studentId;
private String depart;
private ArrayList<String> lecture;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getStudentId() {
    return studentId;
}

public void setStudentId(int studentId) {
    this.studentId = studentId;
}

public String getDepart() {
    return depart;
}

public void setDepart(String depart) {
    this.depart = depart;
}

public ArrayList<String> getLecture() {
    return lecture;
}

public void setLecture(ArrayList<String> lecture) {
    this.lecture = lecture;
}

}

StudentInfo类

 package com.tistory.johnmarc;

/**
 * Created by JJH on 2016-07-11.
 */
public class StudentInfo {
    private Student student;

    public void setStudent(Student student) {
        this.student = student;
    }
public void getStudentInfo(){
    System.out.println(student.getName());
    System.out.println(student.getStudentId());
    System.out.println(student.getDepart());
    System.out.println(student.getLecture());
    System.out.println("=========================");
}

}

spring配置xml文件

<bean id="student1" class="com.tistory.johnmarc.Student">
    <property name="name" value="장정현"/>
    <property name="studentId">
        <value>123</value>
    </property>
    <property name="depart">
        <value>software</value>
    </property>
    <property name="lecture" >
      <!-- Problem is there -->
        <list>
            <value>database</value>
            <value>OOAD</value>
        </list>
    </property>
</bean>

我写了上面的代码。

  

错误消息'java.util.ArrayList'类型的属性不能通过'List'注入

知道怎么解决吗?

2 个答案:

答案 0 :(得分:1)

尝试相反的方法 - 将您的Student类更改为使用List,而不是ArrayList。 Student课程不需要知道List实现。

所以

private ArrayList<String> lecture;

应该是

private List<String> lecture;

同样的吸气剂和放大器setter需要改为:

public List<String> getLecture() {
    return lecture;
}

public void setLecture(List<String> lecture) {
    this.lecture = lecture;
}

答案 1 :(得分:0)

请试试这个:

<bean id="student1" class="com.tistory.johnmarc.Student">
<property name="name" value="장정현"/>
<property name="studentId">
    <value>123</value>
</property>
<property name="depart">
    <value>software</value>
</property>
<property name="lecture" >
  <!-- Changes start -->
    <util:list list-class="java.util.ArrayList">
        <value>database</value>
        <value>OOAD</value>         
    </util:list>
  <!-- Changes end -->
</property>

参考: Spring Lists proprties