【发布时间】:2023-03-21 23:31:01
【问题描述】:
我使用 Spring Boot 开发了一个 REST 服务。在一个 REST 控制器中,我有一个基于字段的依赖注入,我喜欢将其更改为基于构造函数的依赖注入。我的依赖注入设置目前如下所示:
@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
}
使用此设置一切正常。我想将 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
}
在更改为基于构造函数的依赖注入之后,当我尝试像 parameterDateService.postParameterDate(parameterDate); 那样注入依赖时,我得到一个 NullPointerException。当我将它设置为基于字段的依赖注入时,我以相同的方式注入,并且没有给出NullPointerException。 ParameterDate 的基于构造函数的依赖注入按预期工作。
我做错了什么?
【问题讨论】:
-
您必须在第二个构造函数上添加 Autowired。或者删除第一个。您还应该将其公开:没有反射就不能调用的构造函数有什么意义?如果您对此感到满意,那么现场注入也可以。
标签: java spring spring-boot dependency-injection