Spring @Autowire 关于属性 vs 构造函数 [英] Spring @Autowire on Properties vs Constructor

查看:21
本文介绍了Spring @Autowire 关于属性 vs 构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So since I've been using Spring, if I were to write a service that had dependencies I would do the following:

@Component
public class SomeService {
     @Autowired private SomeOtherService someOtherService;
}

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

I have now run across code that uses another convention to achieve the same goal

@Component
public class SomeService {
    private final SomeOtherService someOtherService;

    @Autowired
    public SomeService(SomeOtherService someOtherService){
        this.someOtherService = someOtherService;
    }
}

这两种方法都行,我明白.但是使用选项 B 有什么好处吗?对我来说,它在类和单元测试中创建了更多的代码.(必须编写构造函数并且无法使用@InjectMocks)

Both of these methods will work, I understand that. But is there some advantage to using option B? To me, it creates more code in the class and unit test. (Having to write constructor and not being able to use @InjectMocks)

有什么我遗漏的吗?除了向单元测试添加代码之外,自动装配的构造函数还有什么作用吗?这是进行依赖注入的更首选方式吗?

Is there something I'm missing? Is there anything else the autowired constructor does besides add code to the unit tests? Is this a more preferred way to do dependency injection?

推荐答案

是的,选项 B(称为构造函数注入)实际上比字段注入更推荐,并且有几个优点:

Yes, option B (which is called constructor injection) is actually recommended over field injection, and has several advantages:

  • 明确标识了依赖项.在测试或在任何其他情况下实例化对象(例如在配置类中显式创建 bean 实例)时,没有办法忘记一个
  • 依赖项可以是最终的,这有助于提高健壮性和线程安全性
  • 您不需要反射来设置依赖项.InjectMocks 仍然可用,但不是必需的.您可以自己创建模拟并通过简单地调用构造函数来注入它们

有关更详细的文章,请参阅这篇博文,由 Spring 贡献者之一 Olivier Gierke 提供.

See this blog post for a more detailed article, by one of the Spring contributors, Olivier Gierke.

这篇关于Spring @Autowire 关于属性 vs 构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆