有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

SpringREST控制器中的java实例化模型

我只需要简短地解释一下我的spring web应用程序中我不完全理解的一部分

我有一个简单的mvc spring web应用StudentController。对于数据,我有一个类StudentDataModelStub,它实现了IStudentDataModel接口,它有一些简单的函数来处理StudentDataModelStub类中List存储的数据

在{}课上我有

@Autowired private IStudentDataModel model;

当我删除@Autowired注释时,我得到了预期的NullPointerException,因为我没有实例化StudentDataModelStub。但是spring如何知道用哪个类实例化IStudentDataModel,因为多个类可以实现IStudentDataModel接口,以及为什么model必须是@Autowired

这是StudentDataModelStub类的一部分

public class StudentDataModelStub implements IStudentDataModel {

private final Map<Integer, Student> data = new HashMap<>();

@Override
public List<Student> getStudents() {
    // TODO Auto-generated method stub
    return new ArrayList<>(data.values());
}

@Override
public Student getStudent(int id) throws IdNotFoundException {
    // TODO Auto-generated method stub
    if(!data.containsKey(id)){
        throw new IdNotFoundException("...");
    }

    return data.get(id);

}

共 (1) 个答案

  1. # 1 楼答案

    When I delete @Autowired annotation I get NullPointerException which is expected, because I don't instantiate StudentDataModelStub. But how does the spring knows which class to instantiate IStudentDataModel with, because multiple classes can implement IStudentDataModel interface?

    Spring容器扫描@Componentscan(或<context:component-scan>内xml)中指定的包内的依赖项,并将它们注入bean

    现在,关于注入哪个实现,您可以从Spring文档中找到以下文本(也可以查看here)(我的重点)

    @Primary is an effective way to use autowiring by type with several instances when one primary candidate can be determined. When more control over the selection process is required, Spring’s @Qualifier annotation can be used. You can associate qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument.

    简而言之,如果为同一个interface定义了多个实现,那么需要通过指定@Primary@Qualifier来告诉容器要注入哪个bean

    Why model must be @Autowired?

    你的StudentDataModelStub类实际上不是一个模型(实体)类,它实际上是在缓存学生的数据,并根据id返回数据