【问题标题】:Dependency Injection without constructor in Spring BootSpring Boot中没有构造函数的依赖注入
【发布时间】:2021-05-25 12:00:43
【问题描述】:

我是 Spring / Spring Boot 的初学者,我查看了一些 Spring / Spring Boot 项目并意识到,在其中一些项目中,DI 是使用构造函数应用的,如下所示:

@RestController
@RequestMapping("/api/v1/core")
public class DemoController {

    private final SalaryService salaryService;
    private final EmployeeService employeeService;

    public DemoController(SalaryService salaryService, EmployeeService employeeService) {
        this.salaryService = salaryService;
        this.employeeService = employeeService;
    }
}

但是,在某些项目中,DI 是通过注释应用的,并且代码被简化了。是否可以在 Spring 或 Spring Boot 中使用注释并通过删除构造函数来简化代码?如果是这样,是否适用于 Service、Repository 和 Controller?

【问题讨论】:

  • 你展示的方式,没有Autowired注解,那么你是如何应用DI的呢?您也可以自动装配变量本身,这不必在构造函数上
  • @Stultuske 在组件中(例如 RestController),ctor 上的 Autowired 注解完全是可选的。
  • @Stultuske 为什么不发布答案而不是文字?
  • @Maxwell 答案也是“只是文字”。其次,我的意思是评论,而不是答案
  • @Maxwell 好吧,考虑一下。您已经告诉 Spring 它需要通过使用 @RestController 注释类来实例化该类。您的班级恰好有 1 个构造函数。 Spring 足够聪明,可以看出这里没有歧义;如果它想实例化这个类,它必然必须使用那个构造函数。在构造函数中添加@Autowired 对 Spring 没有帮助,它只是额外的噪音。如果你有 2 个构造函数并且你想指示 Spring 选择哪个构造函数,我相信你可以在构造函数上使用 @Autowired,但我从来不需要那个功能。

标签: java spring spring-boot jpa dependency-injection


【解决方案1】:

您可以通过添加@RequiredArgsConstructor 来使用Lombok

@RestController
@RequestMapping("/api/v1/core")
@RequiredArgsConstructor
public class DemoController {

    private final SalaryService salaryService;
    private final EmployeeService employeeService;

}

是的,它适用于服务、存储库和控制器。 您也可以在字段或设置器上使用 @Autowired 注释,但这种方式不是首选。更多细节在这里:Spring @Autowire on Properties vs Constructor

【讨论】:

  • 感谢朋友,投了赞成票。但我需要进一步的解释。
  • 你的意思是@Autowired一般不是首选吗?或用于依赖注入。请进一步解释?
猜你喜欢
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2011-02-02
相关资源
最近更新 更多