原文链接: dryydrydrdconstructor-injection-in-spring
1. Introduction
Arguably one of the most important development principles of modern software design is Dependency Injection (DI), which quite naturally flows out of another critically important principle: Modularity.
可以说,在现代的软件设计中,最重要的开发准则就是依赖注入DI,它也能自然而然的实现一个重要的编程概念:模块化。
This quick tutorial will explore a specific type of DI technique within Spring called Constructor-Based Dependency Injection, which simply put, means that we pass the required components into a class at the time of instantiation.
在这篇文章中,我们将探究一种Spring框架中名为基于构造函数依赖注入的一种技术,简单来说,就是在初始化阶段,把bean对象的所需的依赖设置上。
To get started, we need to import the spring-context dependency in our pom.xml:
为了达到上述上的,需要在pom.xml文件中加入spring-context的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
Then we need to set up a Configuration file. This file can be either a POJO or an XML file, based on preference.
之后,我们需要定义一个配置文件,可以是一个Java类或XML文件,看你的喜好了。
2. Annotation Based Configuration 基于注解的配置方式
Java configuration files look similar to Java objects with some additional annotations:
Java配置类,看起来就像普通的java对象,只不过多了一些额外的注解罢了。
@Configuration
@ComponentScan("c