SpringBoot 构造器注入、Setter方法注入和Field注入对比
0. 引入
今天在看项目代码的时候发现在依赖注入的时候使用了构造器注入,之前使用过 Field 注入和 Setter 方法注入,对构造器注入不是很了解。经过查阅资料看到,Spring 推荐使用构造器注入的方式,下面介绍构造器注入到底有什么玄机。
1. 常见的三种注解注入方式对比
Field 注入
@Controller
public class HelloController {
@Autowired
private AlphaService alphaService;
@Autowired
private BetaService betaService;
}
field 注入方式是使用最多的,原因是这种方式使用起来非常简单,代码更加简洁。
Setter 方法注入
@Controller
public class HelloController {
private AlphaService alphaService;
private BetaService betaService;
@Autowired
public void setAlphaService(AlphaService alphaService) {
this.alphaService = alphaService;
}
@Autowired
public void setBetaService(BetaService betaService) {
this.betaService = betaService;
}
}
在 Spring 3.x 刚推出的时候,Spring 官方在对比构造器注入和 Setter 注入时,推荐使用 Setter 方法注入:
Spring 3.x Constructor-based or setter-based DI?
The Spring team generally advocates setter injection, because large numbers of constructor arguments can get unwieldy, especially when properties are optional. Setter methods also make objects of that class amenable to reconfiguration or re-injection later. Management through JMX MBeans is a compelling use case.
Some purists favor constructor-based injection. Supplying all object dependencies means that the object is always returned to client (calling) code in a totally initialized state. The disadvantage is that the object becomes less amenable to reconfiguration and re-injection.
意思是说,当出现很多注入项的时候,构造器参数可能会变得臃肿,特别是当参数时可选的时候。Setter 方式注入可以让类在之后重新配置和重新注入;
Constructor 注入
@Controller
public class HelloController {
private final AlphaService alphaService;
private final BetaService betaService;
@Autowired
public HelloController(AlphaService alphaService, BetaService betaService) {
this.alphaService = alphaService;
this.betaService = betaService;
}
}
Spring 4.x 的时候,Spring 官方在对比构造器注入和 Setter 注入时,推荐使用构造器注入方式:
Spring 4.x Constructor-based or setter-based 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. Management through JMX MBeans is therefore a compelling use case for setter injection.
因为使用构造器注入方式注入的组件不可变,且保证了需要的依赖不为 null。此外,构造器注入的组件总是能够在完全初始化的状态返回给客户端(调用方);对于很多参数的构造器说明可能包含了太多了职责,违背了单一职责原则,表示代码应该重构来分离职责到合适的地方。
2. 构造器注入还是 Setter 注入?
在对比 Setter 方法注入和 构造器注入的时候 分别引用的 Spring 官方文档的第二段阐述了除推荐方式的另一种方式的特点。
在 Spring 3.x 的时候 Spring 推荐 Setter 方法注入,第二段表示:一些纯粹主义者喜欢基于构造函数的注入。提供所有对象依赖项意味着对象总是在完全初始化状态下返回给客户机(调用)代码。缺点是对象不太容易重新配置和重新注入。
在 Spring 4.x 的时候 Spring 推荐构造器注入,第二段表示:Setter 注入应该主要用于可选的依赖项,这些依赖项可以在类中分配合理的默认值。否则,必须在代码使用依赖项的任何地方执行非空检查。setter 注入的一个好处是,setter 方法使该类的对象能够在以后重新配置或重新注入。
Setter 注入应该被用于可选依赖项。当没有提供它们时,类应该能够正常工作。在对象被实例化之后,依赖项可以在任何时候被更改。
构造器注入有利于强制依赖。通过在构造函数中提供依赖,您可以确保依赖对象在被构造时已准备好被使用。在构造函数中赋值的字段也可以是final的,这使得对象是完全不可变的,或者至少可以保护其必需的字段。
构造器注入还可以避免 Field 注入的循环依赖问题,比如 在 Alpha 中注入 Beta,又在 Beta 中注入 Alpha。如果使用构造器注入,在 Spring 启动的时候就会抛出 BeanCurrentlyInCreationException 提醒循环依赖。
参考:
https://www.vojtechruzicka.com/field-dependency-injection-considered-harmful/
SpringBoot 构造器注入、Setter方法注入和Field注入对比的更多相关文章
- Spring 基于设值函数(setter方法)的依赖注入
当容器调用一个无参的构造函数或一个无参的静态 factory 方法来初始化你的 bean 后,通过容器在你的 bean 上调用设值函数,基于设值函数的 DI 就完成了. 下述例子显示了一个类 Text ...
- Java学习笔记(十七):构造器和setter方法选用
- Spring官网阅读(二)(依赖注入及方法注入)
上篇文章我们学习了官网中的1.2,1.3两小节,主要是涉及了容器,以及Spring实例化对象的一些知识.这篇文章我们继续学习Spring官网,主要是针对1.4小节,主要涉及到Spring的依赖注入.虽 ...
- 吴裕雄--天生自然JAVA SPRING框架开发学习笔记:Spring DI(依赖注入)的实现方式属性注入和构造注入
依赖注入(Dependency Injection,DI)和控制反转含义相同,它们是从两个角度描述的同一个概念. 当某个 Java 实例需要另一个 Java 实例时,传统的方法是由调用者创建被调用者的 ...
- Java开发学习(七)----DI依赖注入之自动装配与集合注入
一.自动配置 上一篇博客花了大量的时间把Spring的注入去学习了下,总结起来就两个字麻烦.麻烦在配置文件的编写配置上.那有更简单方式么?有,自动配置 1.1 依赖自动装配 IoC容器根据bean所依 ...
- Spring第六弹—-依赖注入之使用构造器注入与使用属性setter方法注入
所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中. 使用构造器注入 1 2 3 4 <constructor-arg index=“0” type=“java.lang. ...
- 哪种依赖注入方式你建议使用,构造器注入,还是 Setter方法注入?
你两种依赖方式都可以使用,构造器注入和Setter方法注入.最好的解决方案是用构造器参数实现强制依赖,setter方法实现可选依赖.
- Spring-Context之六:基于Setter方法进行依赖注入
上文讲了基于构造器进行依赖注入,这里讲解基于Setter方法进行注入.在Java世界中有个约定(Convention),那就是属性的设置和获取的方法名一般是:set+属性名(参数)及get+属性名() ...
- spring构造函数注入、setter方法注入和接口注入
Spring开发指南中所说的三种注入方式: Type1 接口注入 我们常常借助接口来将调用者与实现者分离.如: public class ClassA { private InterfaceB clz ...
随机推荐
- 自动调度GPU的卷积层
自动调度GPU的卷积层 这是有关如何对GPU使用自动调度程序的文档. 与依靠手动模板定义搜索空间的基于模板的autotvm不同,自动调度程序不需要任何模板.用户只需要编写计算声明,而无需任何调度命令或 ...
- ARM-CPU卷积网络的自动调谐
ARM-CPU卷积网络的自动调谐 为特定的ARM设备自动调谐对于获得最佳性能至关重要.这是一个关于如何调整整个卷积网络的资料. 以模板的形式编写了TVM中ARM CPU的操作实现.模板有许多可调旋钮( ...
- thymeleaf+Springboot实现自定义标签
在项目开发中,有一些组件不能满足我们快速开发的要求,我们需要封装一些组件来更加的便利我们.比如,我们可以封装一个下拉框组件,只要开发人员只有引用这个组件的标签,就能出现效果,而不用再去请求url,渲染 ...
- 浅谈lambda表达式<最通俗易懂的讲解
Java8发布已经有一段时间了,这次发布的改动比较大,很多人将这次改动与Java5的升级相提并论.Java8其中一个很重要的新特性就是lambda表达式,允许我们将行为传到函数中.想想看,在Java8 ...
- Linux命令大全之基本命令
命令提示符中: ~:表示家目录 #:表示超级用户 $:表示普通用户 命令 [选项] [参数] ls(list):查询目录中的内容 ls [选项] [文件或目录] -a:显示所有文件, ...
- Windows内核开发-Windows内部概述-2-
Windows内部概述-2- 线程: 执行代码的实体是线程.一个线程的包含在进程里面的,线程使用进程提供的资源来运行代码. 一个线程拥有以下的内容: 1:明确的运行模式,用户态或者内核态. 2:执行的 ...
- js笔记9
1.面向对象 js一开始就是写网页特效,面向过程的,作者发现这样写不好,代码重复利用率太高,计算机内存消耗太大,网页性能很差,所以作者就受到了java和c语言的影响,往面向对象靠齐.js天生有一个Ob ...
- Qt 新手实战项目之手把手打造一个串口助手
一前景 很多时候我们在学习一门新的语言,一直在学习各种语法和记住各种关键字,很容易产生枯燥的情绪,感觉学习这些玩意儿不知道用在什么地方,心里很是苦恼,这不,我在这记录下我学习Qt的第一个的小项目-串口 ...
- NoSql非关系型数据库之MongoDB应用(二):安装MongoDB可视化工具
业精于勤,荒于嬉:行成于思,毁于随. 我们上次说到NoSql非关系型数据库之MongoDB应用(一):安装MongoDB服务 这次我们介绍安装 NoSQL Manager for MongoDB 可 ...
- nexus AD 集成配置
nexus AD 集成配置 管理用户登录 点击设置图标-->LDAP-->Create connection 进入AD 集成配置页面 Connection配置 User and group ...