因此,由于我一直在使用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)
有什么我想念的吗?除了将代码添加到单元测试中之外,自动装配构造函数还有其他功能吗?这是进行依赖注入的更优选的方法吗?
是的,实际上建议使用选项B(称为构造函数注入),而不是使用字段注入,它具有几个优点: