究竟什么是场注入以及如何避免它? [英] What exactly is Field Injection and how to avoid it?

查看:108
本文介绍了究竟什么是场注入以及如何避免它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些关于 Spring MVC 和 Portlet 的帖子中读到,不推荐字段注入.据我了解,字段注入是指像这样使用 @Autowired 注入 Bean:

I read in some posts about Spring MVC and Portlets that field injection is not recommended. As I understand it, field injection is when you inject a Bean with @Autowired like this:

@Component
public class MyComponent {
    @Autowired
    private Cart cart;
}

在我的研究中,我还阅读了构造函数注入:

During my research I also read about constructor injection:

@Component
public class MyComponent {
    private final Cart cart;

    @Autowired
    public MyComponent(Cart cart){
       this.cart = cart;
    }
}

这两种注射的优缺点是什么?

What are the advantages and the disadvantages of both of these types of injections?

编辑 1: 因为这个问题被标记为 这个问题 我查过了.因为在问题和答案中都没有任何代码示例,我不清楚我对我正在使用的注入类型的猜测是否正确.

EDIT 1: As this question is marked as duplicate of this question i checked it. Cause there aren't any code examples neither in the question nor in the answers it's not clear to me if i'm correct with my guess which injection type i'm using.

推荐答案

注入类型

关于如何将依赖项注入到 bean 中,有三个选项:

There are three options for how dependencies can be injected into a bean:

  1. 通过构造函数
  2. 通过 setter 或其他方法
  3. 通过反射,直接进入领域

您正在使用选项 3.这就是您直接在您的字段上使用 @Autowired 时发生的情况.

You are using option 3. That is what is happening when you use @Autowired directly on your field.

注射指南

一般准则,即Spring 推荐(请参阅 Constructor-based DISetter-based DI) 如下:

A general guideline, which is recommended by Spring (see the sections on Constructor-based DI or Setter-based DI) is the following:

  • 对于强制依赖或以不变性为目标时,请使用构造函数注入
  • 对于可选或可更改的依赖项,请使用 setter 注入
  • 在大多数情况下避免字段注入

场注入缺点

字段注入不受欢迎的原因如下:

The reasons why field injection is frowned upon are as follows:

  • 您不能像构造函数注入一样创建不可变的对象
  • 你的类与你的 DI 容器紧密耦合,不能在它之外使用
  • 您的类无法在没有反射的情况下实例化(例如在单元测试中).您需要 DI 容器来实例化它们,这使您的测试更像集成测试
  • 你真正的依赖是从外部隐藏的,不会反映在你的接口(构造函数或方法)中
  • 拥有十个依赖项真的很容易.如果您使用构造函数注入,您将拥有一个带有 10 个参数的构造函数,这将表明某些事情是可疑的.但是您可以无限期地使用字段注入来添加注入的字段.依赖过多是一个危险信号,表明该类通常会做不止一件事情,并且可能违反单一职责原则.

结论

根据您的需要,您应该主要使用构造函数注入或构造函数和 setter 注入的某种混合.场注入有很多缺点,应该避免.字段注入唯一的优点就是写起来更方便,不失为一个利弊.

Depending on your needs, you should primarily use constructor injection or some mix of constructor and setter injection. Field injection has many drawbacks and should be avoided. The only advantage of field injection is that it is more convenient to write, which does not outweigh all the cons.

进一步阅读

我写了一篇关于为什么通常不推荐字段注入的博客文章:字段依赖注入被认为是有害的.

I wrote a blog article about why field injection is usually not recommended: Field Dependency Injection Considered Harmful.

这篇关于究竟什么是场注入以及如何避免它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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