简体   繁体   English

基于Spring Boot构造函数的依赖注入不起作用

[英]Spring Boot Constructor Based Dependency Injection not working

I've used Spring Boot to develop a REST Service. 我已经使用Spring Boot开发了REST服务。 In one of the REST controllers I have a field based dependency injection that I like to change to a constructor based dependency injection. 在一个REST控制器中,我有一个基于字段的依赖项注入,我希望将其更改为基于构造函数的依赖项注入。 My setup of the dependency injections currently looks like this: 我的依赖项注入当前设置如下:

@RestController
public class ParameterDateController {

    private ParameterDateController() {
    }

    private ParameterDate parameterDate;

    private ParameterDateController(ParameterDate parameterDate) {
        this.parameterDate = parameterDate;
    }

    @Autowired
    private ParameterDateService parameterDateService;

// here are the metods of the endpoints
}

With this setup everything works fine. 通过此设置,一切正常。 I would likt to change ParameterDateService to constructor based and I tried with this: 我会likt改变ParameterDateService基于构造函数,我试着用这样的:

@RestController
public class ParameterDateController {

    private ParameterDateController() {
    }

    private ParameterDate parameterDate;

    private ParameterDateController(ParameterDate parameterDate) {
        this.parameterDate = parameterDate;
    }

    private ParameterDateService parameterDateService;

    private ParameterDateController(ParameterDateService parameterDateService) {
        this.parameterDateService = parameterDateService;
    }

// here are the metods of the endpoints
}

After the change to constructor based dependency injection I get a NullPointerException when I try to inject the dependency like this parameterDateService.postParameterDate(parameterDate); 更改为基于构造函数的依赖项注入后,当我尝试像这种parameterDateService.postParameterDate(parameterDate);那样注入依赖项时,我得到了NullPointerException parameterDateService.postParameterDate(parameterDate); . I inject the same way when I have it setup as field based dependency injection and that gives no NullPointerException . 我将其设置为基于字段的依赖项注入时以相同的方式注入,但没有给出NullPointerException The constructor based dependency injection for ParameterDate works as expected. 基于构造函数的ParameterDate依赖项注入按预期方式工作。

What is it I'm doing wrong? 我做错了什么?

If you want to have two dependencies wired via constructor - you have to declare them as constructor parameters, so here you have to declare: 如果要通过构造函数连接两个依赖项,则必须将它们声明为构造函数参数,因此在这里必须声明:

public ParameterDateController(ParameterDate parameterDate, ParameterDateService parameterDateService) {
    this.parameterDate = parameterDate;
    this.parameterDateService = parameterDateService;
}

Here's a good answer about constructor injection. 这是关于构造函数注入的好答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM