相关疑难解决方法(0)

Spring @Autowire on Properties vs Constructor

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

@Component
public class SomeService {
     @Autowired private SomeOtherService someOtherService;
}
Run Code Online (Sandbox Code Playgroud)

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

@Component
public class SomeService {
    private final SomeOtherService someOtherService;

    @Autowired
    public SomeService(SomeOtherService someOtherService){
        this.someOtherService = someOtherService;
    }
}
Run Code Online (Sandbox Code Playgroud)

我理解这两种方法都有效.但是使用选项B有一些优势吗?对我来说,它在类和单元测试中创建了更多代码.(必须编写构造函数而不能使用@InjectMocks)

有什么我想念的吗?除了在单元测试中添加代码之外,还有其他任何自动装配的构造函数吗?这是一种更优先的依赖注入方式吗?

spring constructor dependency-injection autowired

111
推荐指数
7
解决办法
4万
查看次数