Spring / JPA / Hibernate 中的构造函数注入



Spring 和 JPA 的新功能

我有以下控制器类

public class RegisterStudent{
    private StudentInfo studentInfo;
    private RegisterStudentHelper studentHelper;
    public  void registerStudentProcess(String name,String regNo,String course)
    {
       // // Creating an Instance of StudentInfo Class
        studentInfo = new StudentInfo();
        studentInfo.setName(name);
        studentInfo.setRegNo(regNo);
        studentInfo.setCourse(course);
        // set the StudentInfo to the RegisterStudentHelper constructor
        studentHelper = new RegisterStudentHelper(studentInfo);
        studentHelper.doRegisterStudentProcess();
    }   
}

我正在尝试在使用Spring,JPA和hibernate时转换相同的模型,

如下所示
    @Controller
    public class RegisterStudent{
            @Autowired
            private StudentInfo studentInfo;
            @Autowired
            private RegisterStudentHelper studentHelper;
            public  void registerStudentProcess(String name,String regNo,String course)
        {
            studentInfo.setName(name);
            studentInfo.setRegNo(regNo);
            studentInfo.setCourse(course);
            studentHelper = new RegisterStudentHelper(studentInfo);
            studentHelper.doRegisterStudentProcess();
    }
}

如何使用注释来设置学生信息以注册学生助手构造函数?

任何想法或建议都值得赞赏。

首先关注Roland Illig的评论!

Spring(和其他一些 DI 框架(允许 3 种类型的依赖注入:

1.属性注入

@Autowired
private AnyBeanClazz anyBean;

2.方法注入

@Autowired
public void injectedMethod(AnyBeanClazz anyBean){
    // Do anything here
}

3.构造函数注入

class OtherBeanClazz{
    @Autowired
    public OtherBeanClazz(AnyBeanClazz anyBean){}
}

看完你的例子,我可以假设StudentInfo是一个值对象,RegisterStudentHelper是一个服务对象。由于值对象包含状态,因此它们不是依赖项注入的最佳候选项。您应该将其创建为新的,并将其作为参数传递给doRegisterStudentProcess((方法。

我发现了这篇文章供您理解:https://www.bennadel.com/blog/2377-creating-service-objects-and-value-objects-in-a-dependency-injection-di-framework.htm

好吧,您的代码对我来说没有多大意义,因为在某些部分您在StudentInfo上设置了值,如果您将其用作 Spring 注入的@Component,则默认情况下这将是一个 Singleton 类。

但是,这是使用构造函数注入的代码:

@Controller
public class RegisterStudent {
    private RegisterStudentHelper studentHelper;
    private StudentInfo studentInfo;
    @Autowired
    RegisterStudent(StudentInfo studentInfo ) {
        this.studentInfo = studentInfo;
        this.studentHelper = studentHelper;
    }
}

如果你愿意,你可以省略@Autowired,因为Spring足够聪明,知道如果一个Controller(或任何@Component(只有一个构造函数,他会自动使用注入。

最新更新