【问题标题】:Spring Boot Constructor Based Dependency Injection not working基于 Spring Boot 构造函数的依赖注入不起作用
【发布时间】: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。当我将它设置为基于字段的依赖注入时,我以相同的方式注入,并且没有给出NullPointerExceptionParameterDate 的基于构造函数的依赖注入按预期工作。

我做错了什么?

【问题讨论】:

  • 您必须在第二个构造函数上添加 Autowired。或者删除第一个。您还应该将其公开:没有反射就不能调用的构造函数有什么意义?如果您对此感到满意,那么现场注入也可以。

标签: java spring spring-boot dependency-injection


【解决方案1】:

如果你想通过构造函数连接两个依赖项 - 你必须将它们声明为构造函数参数,所以在这里你必须声明:

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

这是关于构造函数注入的a good answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2011-09-02
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多