小编典典

关于属性vs构造函数的Spring @Autowire

spring

因此,由于我一直在使用Spring,所以如果我要编写一个具有依赖项的服务,我将执行以下操作:

@Component
public class SomeService {
     @Autowired private SomeOtherService someOtherService;
}

我现在遇到了使用另一种约定实现相同目标的代码

@Component
public class SomeService {
    private final SomeOtherService someOtherService;

    @Autowired
    public SomeService(SomeOtherService someOtherService){
        this.someOtherService = someOtherService;
    }
}

我知道这两种方法都行得通。但是使用选项B有一些好处吗?对我来说,它在类和单元测试中创建了更多代码。(必须编写构造函数,而不能使用@InjectMocks)

有什么我想念的吗?除了将代码添加到单元测试中之外,自动装配构造函数还有其他功能吗?这是进行依赖注入的更优选的方法吗?


阅读 428

收藏
2020-04-11

共1个答案

小编典典

是的,实际上建议使用选项B(称为构造函数注入),而不是使用字段注入,它具有几个优点:

  • 依存关系被明确标识。测试或在任何其他情况下实例化对象时,都无法忘记一个方法(例如在config类中显式创建bean实例)
  • 依赖关系可以是最终的,这有助于增强鲁棒性和线程安全性
  • 你不需要反射来设置依赖项。InjectMocks仍然可用,但不是必需的。你可以自己创建模拟并通过调用构造函数将其注入
2020-04-11