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

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

问题描述

因此,由于我一直在使用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:

  • 清楚地确定了依存关系.在测试或在任何其他情况下实例化对象时(例如在config类中显式创建bean实例),都不会忘记一个方法
  • 依赖关系可以是最终的,这有助于增强鲁棒性和线程安全性
  • 您无需进行反射即可设置依赖项. InjectMocks仍然可用,但不是必需的.您可以自己创建模拟并通过调用构造函数将其注入

有关详细信息,请参见此博客文章. ,由一位Spring贡献者 Olivier Gierke .

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

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

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