【发布时间】:2017-03-29 22:26:48
【问题描述】:
所以由于我一直在使用 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)
我有什么遗漏吗?除了向单元测试添加代码之外,自动装配的构造函数还有什么其他功能吗?这是进行依赖注入的更优选方式吗?
【问题讨论】:
-
选项A和选项B哪个是?
标签: spring dependency-injection constructor autowired