Intro to Inversion of Control and Dependency Injection with Spring – 使用Spring的反转控制和依赖注入介绍

最后修改: 2016年 12月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll introduce the concepts of IoC (Inversion of Control) and DI (Dependency Injection), as well as take a look at how these are implemented in the Spring framework.

在本教程中,我们将介绍IoC(反转控制)和DI(依赖注入)的概念,并看看这些概念是如何在Spring框架中实现的。

2. What Is Inversion of Control?

2.什么是反转控制?

Inversion of Control is a principle in software engineering which transfers the control of objects or portions of a program to a container or framework. We most often use it in the context of object-oriented programming.

反转控制是软件工程中的一项原则,它将对象或程序的一部分的控制权转移到一个容器或框架中。我们最常在面向对象编程的背景下使用它。

In contrast with traditional programming, in which our custom code makes calls to a library, IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built in. If we want to add our own behavior, we need to extend the classes of the framework or plugin our own classes.

与传统编程相比,我们的自定义代码会调用一个库,而IoC使框架能够控制程序的流程并调用我们的自定义代码。为了实现这一点,框架使用了内建有额外行为的抽象概念。如果我们想添加自己的行为,我们需要扩展框架的类或插入自己的类。

The advantages of this architecture are:

这种架构的优势在于。

  • decoupling the execution of a task from its implementation
  • making it easier to switch between different implementations
  • greater modularity of a program
  • greater ease in testing a program by isolating a component or mocking its dependencies, and allowing components to communicate through contracts

We can achieve Inversion of Control through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).

我们可以通过各种机制来实现反转控制,例如。策略设计模式、服务定位模式、工厂模式和依赖注入(DI)。

We’re going to look at DI next.

我们接下来要看的是DI。

3. What Is Dependency Injection?

3.什么是依赖性注入?

Dependency injection is a pattern we can use to implement IoC, where the control being inverted is setting an object’s dependencies.

依赖注入是一种我们可以用来实现IoC的模式,其中被倒置的控制是设置一个对象的依赖关系。

Connecting objects with other objects, or “injecting” objects into other objects, is done by an assembler rather than by the objects themselves.

将对象与其他对象连接起来,或者将对象 “注入 “到其他对象中,是由汇编者而不是由对象本身来完成的。

Here’s how we would create an object dependency in traditional programming:

下面是我们在传统编程中创建对象依赖的方法。

public class Store {
    private Item item;
 
    public Store() {
        item = new ItemImpl1();    
    }
}

In the example above, we need to instantiate an implementation of the Item interface within the Store class itself.

在上面的例子中,我们需要在Store类本身中实例化一个Item接口。

By using DI, we can rewrite the example without specifying the implementation of the Item that we want:

通过使用DI,我们可以重写这个例子,而不必指定我们想要的Item的实现。

public class Store {
    private Item item;
    public Store(Item item) {
        this.item = item;
    }
}

In the next sections, we’ll look at how we can provide the implementation of Item through metadata.

在接下来的章节中,我们将看看我们如何通过元数据提供Item的实现。

Both IoC and DI are simple concepts, but they have deep implications in the way we structure our systems, so they’re well worth understanding fully.

IoC和DI都是简单的概念,但它们对我们构造系统的方式有很深的影响,所以它们非常值得充分理解。

4. The Spring IoC Container

4.Spring IoC容器

An IoC container is a common characteristic of frameworks that implement IoC.

IoC容器是实现IoC的框架的一个共同特征。

In the Spring framework, the interface ApplicationContext represents the IoC container. The Spring container is responsible for instantiating, configuring and assembling objects known as beans, as well as managing their life cycles.

在Spring框架中,接口ApplicationContext代表IoC容器。Spring容器负责实例化、配置和组装被称为beans的对象,并管理其生命周期。

The Spring framework provides several implementations of the ApplicationContext interface: ClassPathXmlApplicationContext and FileSystemXmlApplicationContext for standalone applications, and WebApplicationContext for web applications.

Spring框架提供了ApplicationContext接口的几种实现。ClassPathXmlApplicationContextFileSystemXmlApplicationContext适用于独立应用程序,而WebApplicationContext适用于Web应用程序。

In order to assemble beans, the container uses configuration metadata, which can be in the form of XML configuration or annotations.

为了组装Bean,容器使用配置元数据,它可以是XML配置或注释的形式。

Here’s one way to manually instantiate a container:

这里有一种手动实例化容器的方法。

ApplicationContext context
  = new ClassPathXmlApplicationContext("applicationContext.xml");

To set the item attribute in the example above, we can use metadata. Then the container will read this metadata and use it to assemble beans at runtime.

为了设置上面例子中的item属性,我们可以使用元数据。然后容器将读取这个元数据并在运行时使用它来组装Bean。

Dependency Injection in Spring can be done through constructors, setters or fields.

Spring中的依赖注入可以通过构造函数、设置函数或字段来完成。

5. Constructor-Based Dependency Injection

5.基于构造函数的依赖注入

In the case of constructor-based dependency injection, the container will invoke a constructor with arguments each representing a dependency we want to set.

基于构造器的依赖注入的情况下,容器将调用一个构造器,每个参数代表我们要设置的依赖。

Spring resolves each argument primarily by type, followed by name of the attribute, and index for disambiguation. Let’s see the configuration of a bean and its dependencies using annotations:

Spring主要通过类型来解析每个参数,然后是属性名称,以及用于消除歧义的索引。让我们看看使用注解对Bean及其依赖关系的配置。

@Configuration
public class AppConfig {

    @Bean
    public Item item1() {
        return new ItemImpl1();
    }

    @Bean
    public Store store() {
        return new Store(item1());
    }
}

The @Configuration annotation indicates that the class is a source of bean definitions. We can also add it to multiple configuration classes.

@Configuration注解表明该类是Bean定义的来源。我们也可以把它添加到多个配置类中。

We use the @Bean annotation on a method to define a bean. If we don’t specify a custom name, then the bean name will default to the method name.

我们在一个方法上使用@Bean注解来定义一个Bean。如果我们不指定一个自定义的名字,那么Bean的名字将默认为方法的名字。

For a bean with the default singleton scope, Spring first checks if a cached instance of the bean already exists, and only creates a new one if it doesn’t. If we’re using the prototype scope, the container returns a new bean instance for each method call.

对于使用默认singleton作用域的Bean,Spring首先检查该Bean的缓存实例是否已经存在,如果不存在则只创建一个新的。如果我们使用prototype作用域,容器就会为每个方法调用返回一个新的bean实例。

Another way to create the configuration of the beans is through XML configuration:

另一种创建Bean配置的方法是通过XML配置。

<bean id="item1" class="org.baeldung.store.ItemImpl1" /> 
<bean id="store" class="org.baeldung.store.Store"> 
    <constructor-arg type="ItemImpl1" index="0" name="item" ref="item1" /> 
</bean>

6. Setter-Based Dependency Injection

6.基于设定器的依赖性注入</strong

For setter-based DI, the container will call setter methods of our class after invoking a no-argument constructor or no-argument static factory method to instantiate the bean. Let’s create this configuration using annotations:

对于基于setter的DI,容器将在调用无参数的构造函数或无参数的静态工厂方法来实例化Bean后调用我们类的setter方法。让我们使用注解来创建这种配置。

@Bean
public Store store() {
    Store store = new Store();
    store.setItem(item1());
    return store;
}

We can also use XML for the same configuration of beans:

我们也可以使用XML来进行同样的豆类配置。

<bean id="store" class="org.baeldung.store.Store">
    <property name="item" ref="item1" />
</bean>

We can combine constructor-based and setter-based types of injection for the same bean. The Spring documentation recommends using constructor-based injection for mandatory dependencies, and setter-based injection for optional ones.

我们可以为同一个Bean结合基于构造器和基于设置器的注入类型。Spring文档建议对强制性的依赖关系使用基于构造函数的注入,而对可选的依赖关系使用基于设置函数的注入。

7. Field-Based Dependency Injection

7.基于现场的依赖注入

In case of Field-Based DI, we can inject the dependencies by marking them with an @Autowired annotation:

在基于字段的DI中,我们可以通过用@Autowired注解标记它们来注入依赖关系。

public class Store {
    @Autowired
    private Item item; 
}

While constructing the Store object, if there’s no constructor or setter method to inject the Item bean, the container will use reflection to inject Item into Store.

在构造 Store 对象时,如果没有构造器或设置器方法来注入 Item Bean,容器将使用反射将 Item 注入 Store

We can also achieve this using XML configuration.

我们也可以使用XML配置来实现。

This approach might look simpler and cleaner, but we don’t recommend using it because it has a few drawbacks such as:

这种方法可能看起来更简单、更干净,但我们不建议使用它,因为它有一些缺点,比如。

  • This method uses reflection to inject the dependencies, which is costlier than constructor-based or setter-based injection.
  • It’s really easy to keep adding multiple dependencies using this approach. If we were using constructor injection, having multiple arguments would make us think that the class does more than one thing, which can violate the Single Responsibility Principle.

More information on the @Autowired annotation can be found in the Wiring In Spring article.

关于@Autowired注解的更多信息可以在Wiring In Spring文章中找到。

8. Autowiring Dependencies

8.自动布线的依赖性

Wiring allows the Spring container to automatically resolve dependencies between collaborating beans by inspecting the beans that have been defined.

Wiring允许Spring容器通过检查已定义的Bean来自动解决协作Bean之间的依赖关系。

There are four modes of autowiring a bean using an XML configuration:

有四种模式可以使用XML配置来自动连接Bean。

  • no: the default value – this means no autowiring is used for the bean and we have to explicitly name the dependencies.
  • byName: autowiring is done based on the name of the property, therefore Spring will look for a bean with the same name as the property that needs to be set.
  • byType: similar to the byName autowiring, only based on the type of the property. This means Spring will look for a bean with the same type of the property to set. If there’s more than one bean of that type, the framework throws an exception.
  • constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments.

For example, let’s autowire the item1 bean defined above by type into the store bean:

例如,让我们把上面定义的item1 Bean按类型自动连接到store Bean中。

@Bean(autowire = Autowire.BY_TYPE)
public class Store {
    
    private Item item;

    public setItem(Item item){
        this.item = item;    
    }
}

We can also inject beans using the @Autowired annotation for autowiring by type:

我们还可以使用@Autowired注解来注入Bean,以便按类型进行自动布线。

public class Store {
    
    @Autowired
    private Item item;
}

If there’s more than one bean of the same type, we can use the @Qualifier annotation to reference a bean by name:

如果有多个相同类型的Bean,我们可以使用@Qualifier注解来引用一个Bean的名字。

public class Store {
    
    @Autowired
    @Qualifier("item1")
    private Item item;
}

Now let’s autowire beans by type through XML configuration:

现在让我们通过XML配置,按类型自动连接Bean。

<bean id="store" class="org.baeldung.store.Store" autowire="byType"> </bean>

Next, let’s inject a bean named item into the item property of store bean by name through XML:

接下来,让我们通过XML将一个名为item的bean注入到storebean的item属性中。

<bean id="item" class="org.baeldung.store.ItemImpl1" />

<bean id="store" class="org.baeldung.store.Store" autowire="byName">
</bean>

We can also override the autowiring by defining dependencies explicitly through constructor arguments or setters.

我们也可以通过构造函数参数或设置器明确定义依赖关系来覆盖自动布线。

9. Lazy Initialized Beans

9.懒惰的初始化豆子

By default, the container creates and configures all singleton beans during initialization. To avoid this, we can use the lazy-init attribute with value true on the bean configuration:

默认情况下,容器会在初始化过程中创建并配置所有的单子Bean。为了避免这种情况,我们可以在Bean配置中使用lazy-init属性,其值为true

<bean id="item1" class="org.baeldung.store.ItemImpl1" lazy-init="true" />

Consequently, the item1 bean will only be initialized when it’s first requested, and not at startup. The advantage of this is faster initialization time, but the trade-off is that we won’t discover any configuration errors until after the bean is requested, which could be several hours or even days after the application has already been running.

因此,item1 Bean只有在第一次被请求时才会被初始化,而不是在启动时。这样做的好处是初始化时间更快,但代价是我们在请求Bean后才会发现任何配置错误,而这可能是在应用程序已经运行了几个小时甚至几天后。

10. Conclusion

10.结论

In this article, we presented the concepts of Inversion of Control and Dependency Injection, and exemplified them in the Spring framework.

在这篇文章中,我们介绍了控制反转和依赖注入的概念,并以Spring框架为例进行了说明。

We can read more about these concepts in Martin Fowler’s articles:

我们可以在Martin Fowler的文章中阅读更多关于这些概念的内容。

Furthermore, we can learn about the Spring implementations of IoC and DI in the Spring Framework Reference Documentation.

此外,我们可以在Spring框架参考文档中了解到IoC和DI的Spring实现。