首页  

spring构造注入优缺点     所属分类 spring 浏览量 919
Spring3.x 推荐 set 注入
之后推荐 构造注入

构造注入优点
保证依赖不可变(final关键字)
保证依赖不为空(省去对依赖检查)
保证对象返回的时候是完全初始化的状态
避免循环依赖(循环依赖会报错  BeanCurrentlyInCreationException)
提升代码的可复用性 ( java 配置类里 直接 new 对象 , 可脱离ioc容器)

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.

构造注入缺点
构造函数参数多笨重
灵活性不强 , 无法修改
多个构造函数 容易歧义
循环依赖会报错
继承处理麻烦


spring3 推荐 set 注入的原因
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.



spring4种注入方式 spring循环依赖

上一篇     下一篇
kafka集群搭建

kafka命令行发送接收消息

zookeeper命令行zkCli使用

springboot 构造注入实例

zookeeper配置参数

dubbo面试题