Spring推荐使用构造器注入,我不推荐

阅读 68

2023-04-11


Field injection:

++ less code to write
-- unsafe code
 - more complicated to test

Constructor injection:


++ safe code
 - more code to write (see the hint to Lombok)
 + easy to test

虽然官方推荐Constructor injection,个人更喜欢Field injection。原因如下: 更少的代码 约定优于配置,都用Field injection也很安全 用spring做单元测试field injection并不复杂


精彩评论(0)

0 0 举报