Field injection is not recommended

在使用IDEA编写Spring时, 可能会遇到warning : Field injection is not recommended.

究竟为什么不推荐Field injection呢?

Field injection是什么?

class MyComponent {

  @Inject MyCollaborator collaborator;

  public void myBusinessMethod() {
    collaborator.doSomething();
  }
}

自动注入成员变量.

乍看下, 真的没什么问题, 我们写的观察者什么的都是这样, 难不成要我们在构造函数注入?

注入的方式, 一般有两种
1. 通过get方式获得
2. 通过constructor方式获得

但是, 这里, 我们必须明白, 第一种方式不是必然执行, 而构造却是必然发生的事情. 换言之, class里的field variable可以通过无参数构造函数来初始化, 这样就可以避免 「nullpointexception」

但是, 我们换种方式想, 为什么field variable不能在初始化的时候进行赋值? 为什么不能添加final值?

用IDE写一下, 就明白… final field variable必须构造时候初始化 (Java的特性), 这就导致Field injection是可变的.

可变性所带来的后果
1. 多线程时, 结果可能不确定
2. 测试, 同上


扩展参考网站:
http://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it

Your classes have tight coupling with DI container and cannot be used outside of it

因为我没进行过spring的test, 上网搜了下,也找不到什么理由要将代码移出spring框架

It is really easy to have like 10 dependencies. If you were using constructor injection, having constructor with 10 arguments will signal that something is fishy. But you can add injected fields using field injection indefinitely. Having too many dependencies is a red flag that the class usually does more than one thing and it may be a violation of a Single Responsibility Principle.

另外, 这我也不知道算不算构造注入的好处, 感觉不像. 他们的解释, 就像”有人吃鱼被骨头弄死了 ,所以我们不要吃鱼”, 因为程序员的自我意识比较差, 所以我们就一起用constructor injection吧!!当然, 我也不否这样的正确性. 因为人也是一个变量.

  • 16
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值