java - Spring 中没有 arg 构造函数否定了基于构造函数的 DI 优点

标签 java spring spring-boot

根据 Spring bean 的定义,POJO 应该有一个无参数的构造函数。 考虑到基于构造函数的 DI 的好处,其中通过查看构造函数本身,我们可以了解它的依赖项是什么,没有参数的构造函数不会消除这一优势。

最佳答案

类(class)用马

基于构造函数的依赖注入(inject)更具预测性,并创建不可变的、完全初始化的对象。基于 Setter 的 DI 用于被视为可选的依赖项,但也允许在稍后阶段进一步重新配置对象。两者都是有效的,都有权衡,因此都被广泛使用。

来自Spring documentation (请参阅基于构造函数或基于 setter 的 DI? 框):

The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. Furthermore constructor-injected components are always returned to client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.

Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.

(重点是我的)

关于java - Spring 中没有 arg 构造函数否定了基于构造函数的 DI 优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116604/

相关文章:

mysql - Spring Data 比较 2 个日期范围

Spring Security 5 OAuth2 客户端与 Gitlab 失败

java - 如何使用自定义参数注释返回自定义 spring 错误响应?

spring boot 2.7.0 不公开 http.server.request 指标

java - 带有@Qualifier 的@Bean 声明不起作用

java - 将 java.sql.date 转换为 java.time.LocalDateTime

Java try-finally 竞争条件?

java - SWT 后台线程阻塞 GUI

java - 对于已排序的 200 万元素数组,Arrays.sort(...) 的效率如何

java - 使用 Spring 3+Hibernate JPA 时发现 JPA 注释类