spring-core-2-20 | 构造器注入 VS. Setter 注入:为什么Spring官方文档的解读会与作者的初心出现偏差

本文主要是介绍spring-core-2-20 | 构造器注入 VS. Setter 注入:为什么Spring官方文档的解读会与作者的初心出现偏差,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

构造器注入VS. Setter 注入

Spring Framework 对构造器注入与Setter 的论点:

来自“Constructor-based or setter-based DI”

“The Spring team generally advocates constructor injection, as it lets
you implement application components as immutable objects and ensures that required dependencies are not null.

Furthermore, constructor-injected components are always returned to the 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.
Management through JMX MBeans is therefore a compelling use case for setter injection.”

这里spring团队以一个讨论的口吻来说的, 建议一般使用构造器注入, 保证注入的对象是一个immutable, 不变的对象, 确保依赖的对象不为空. 这个讲法忽略了一个细节, 其实如果依赖的对象为空或者不存在的话, 可以用另外的方式, 也可以通过构造器方式进行注入, 使用 ObjectProvider 类, 它是一种类型安全的方式, 如果你的依赖注入或依赖查找的方式需要的是一个单一类型的依赖, 这时可以调用它的 getIfAvailable() ,来进行示范性的返回, 等于空的时候就会返回空, 这种方式在 springBoot的场景中经常被用到.

构造器注入的组件通常返回给客户端代码的时候, 是一个完整的初始化状态. 不过呢, 如果构造器的参数过多, 代码看起来就不是十分的良好, 意味着类包含了太多的职责, 不能有太多的输入, 最好进行一下重构(refactored)

Setter注入应该主要仅用于我们的可选性的注入, 另一方面, 如果代码中有用到相关的依赖, 非空检查就是必须的, 我们都知道@Autowired注解是有非空检查的参数的, 而默认可以注入空的对象过来.当然 Setter 注入可以让依赖进行延迟注入, 让对象变得更可配, 这是一个优点

《Expert One-on-One™ J2EE™ Development without EJB™》认为Setter 注入的优点:

来自“Chapter 6. Lightweight Containers and Inversion of Control” 节选

“Advantages of Setter Injection include:

• JavaBean properties are well supported in IDEs.
JavaBean的属性在IDE方面支持良好, 前面讲过, 在 GUI 方面是有用的.

• JavaBean properties are self-documenting.
JavaBean的属性是 自文档 的方式, 通常不需要过多文档说明

• JavaBean properties are inherited by subclasses without the need for any code.
JavaBean的属性通过继承的方式呢, 通常不需要任何的修改, 但是这个通常不应该是个优点, 只是作为面向对象的一个特点

• It’s possible to use the standard JavaBeans property-editor machinery for type conversions if necessary.
因为有 propertyEditor 这个机制, setter中可以进行一些类型转换

• Many existing JavaBeans can be used within a JavaBean-oriented IoC
container without modification.
大量存在的JavaBeans可以在JavaBean原生的IoC容器中使用, 不需要做太大的修改.
这里就是指的原生的 BeanContext 这个容器, 这个上下文其实和 spring的 ApplicationContext 有异曲同工之处.

• If there is a corresponding getter for each setter (making the property readable, as well as writable), it is possible to ask the component for its current configuration state. This is particularly useful if we want to persist that state: for example, in an XML form or in a database. With Constructor Injection, there’s no way to find the current state.
如果每一个Setter方法都有对应的Getter方法的情况下, 可以比较方便的在任何时候获取到组件的当前状态.这个特点在我们需要保存这个状态的时候特别有用, 而构造器注入就做不到这点. 这样就容易对Bean进行一个管理.

• Setter Injection works well for objects that have default values, meaning that not all properties need to be supplied at runtime.
Setter方法可以为属性设置一个默认值, 并不是所有的属性都需要在运行时才进行设值.

《Expert One-on-One™ J2EE™ Development without EJB™》认为Setter 注入的缺点:

来自“Chapter 6. Lightweight Containers and Inversion of Control” 节选

“Disadvantages include:

The order in which setters are called is not expressed in any contract. Thus, we sometimes need to invoke a method after the last setter has been called to initialize the component. Spring provides the org.springframework.beans.factory.InitializingBean interface for
this; it also provides the ability to invoke an arbitrary init method. However, this contract must be documented to ensure correct use outside a container.
setter的顺序无法保证, 而构造器注入因为构造器方法的参数顺序是一定的, 天然决定了设值的顺序是有序的, 不会因为外部调用的顺序而出现问题.
这里提到了一个spring的接口 InitializingBean ,这个接口能够帮助我们实现一个特性就是当我的属性已经设置好了之后, 我们再做相应的操作. 但是这个接口并不会强制的保证正确性, 只是一个鼓励.

Not all the necessary setters may have been called before use. The object can thus be left partially configured.”
在调用前并不是每一个Setter方法都需要被调用的.

《Expert One-on-One™ J2EE™ Development without EJB™》认为构造器注入的优点:

来自“Chapter 6. Lightweight Containers and Inversion of Control” 节选

“Advantages of Constructor Injection include:

Each managed object is guaranteed to be in a consistent state—fully configured—before it can be invoked in any business methods. This is the primary motivation of Constructor Injection. (However, it is possible to achieve the same result with JavaBeans via dependency checking, as Spring can optionally perform.) There’s no need for initialization methods.
能够确保每个被管理的对象有一致的状态. 完全配置好的, 且一旦初始化完成就不再进行变更的. 正如前面所说, 也因此组件对应的对象通常也被声明为 final 的.

There may be slightly less code than results from the use of multiple JavaBean methods, although will be no difference in complexity.”
减少过多的Setter和Getter方法的代码量. 这个因为现在有建造模式, 似乎也没啥必要.

《Expert One-on-One™ J2EE™ Development without EJB™》认为构造器注入的缺点:

来自“Chapter 6. Lightweight Containers and Inversion of Control” 节选
这里就能看到, 作者一开始书里的观点, 和后来在spring官方网站的观点, 有一些冲突, 这里反而构造器注入的缺点列了一大堆.

“Disadvantages include:

• Although also a Java-language feature, multi-argument constructors are probably less common in existing code than use of JavaBean properties.
多参数构造器可能会减少代码中一些Bean的使用. 啥意思?

• Java constructor arguments don’t have names visible by introspection.
构造器参数没有一个名称是可见的来提供给外部进行外省或内省.

• Constructor argument lists are less well supported by IDEs than JavaBean setter methods.
IDE的支持不如Setter方法的好

• Long constructor argument lists and large constructor bodies can become
unwieldy.

• Concrete inheritance can become problematic.

• Poor support for optional properties, compared to JavaBeans

• Unit testing can be slightly more difficult

• When collaborators are passed in on object construction, it becomes
impossible to change the reference held in the object. ”

这篇关于spring-core-2-20 | 构造器注入 VS. Setter 注入:为什么Spring官方文档的解读会与作者的初心出现偏差的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/714113

相关文章

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

java中新生代和老生代的关系说明

《java中新生代和老生代的关系说明》:本文主要介绍java中新生代和老生代的关系说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、内存区域划分新生代老年代二、对象生命周期与晋升流程三、新生代与老年代的协作机制1. 跨代引用处理2. 动态年龄判定3. 空间分

解读GC日志中的各项指标用法

《解读GC日志中的各项指标用法》:本文主要介绍GC日志中的各项指标用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、基础 GC 日志格式(以 G1 为例)1. Minor GC 日志2. Full GC 日志二、关键指标解析1. GC 类型与触发原因2. 堆

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析