gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:57:22 26 4
gpt4 key购买 nike

根据 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com