因此,由于我一直在使用 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)
有什么我想念的吗?除了向单元测试添加代码之外,自动装配的构造函数还有什么作用吗?这是进行依赖注入的更优选方法吗?
原文由 GSUgambit 发布,翻译遵循 CC BY-SA 4.0 许可协议
是的,选项 B(称为构造函数注入)实际上比字段注入更推荐,它有几个优点:
有关更详细的文章,请参阅 这篇博客 文章,作者是 Spring 贡献者之一 Olivier Gierke 。