自从我使用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)我是否遗漏了什么?自动装配构造函数除了在单元测试中添加代码之外,还有其他任何作用吗?这是进行依赖注入的更可取方式吗?