Wiring in Spring: @Autowired, @Resource and @Inject 三种注解实现依赖注入

本文主要是介绍Wiring in Spring: @Autowired, @Resource and @Inject 三种注解实现依赖注入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文链接:Wiring in Spring: @Autowired, @Resource and @Inject 

1. Overview 概述

In this Spring Framework tutorial, we'll demonstrate how to use annotations related to dependency injection, namely the @Resource@Inject, and @Autowired annotations. These annotations provide classes with a declarative way to resolve dependencies:

在这篇关于Spring框架的文章中,将会示范如何使用有关依赖注入的注解,即@Resource、@Inject和@Autowired。这些注解提供了一个声明式的方式来配置所需的依赖对象,示例如下:

@Autowired 
ArbitraryClass arbObject;

As opposed to instantiating them directly (the imperative way):

和直接实例化所需对象做对比,示例如下: 

ArbitraryClass arbObject = new ArbitraryClass();

Two of the three annotations belong to the Java extension package: javax.annotation.Resource and javax.inject.Inject. The @Autowired annotation belongs to the org.springframework.beans.factory.annotation package.

上面提及的三个注解中,有两个属性Java扩展包,即 javax.annotaion.Resource 和 javax.inject.Inject。而另一个@Autowired注解则是在 Spring 框架包中。 

Each of these annotations can resolve dependencies either by field injection or by setter injection. We'll use a simplified, but practical example to demonstrate the distinction between the three annotations, based on the execution paths taken by each annotation.

上面的三个注解都可以用到字段或set方法上来实现依赖自动注入,接下来,基于每个注解的执行路径不同,通过一个简单实用的例子来演示它们之间的区别。

The examples will focus on how to use the three injection annotations during integration testing. The dependency required by the test can either be an arbitrary file or an arbitrary class.

这些示例会注重在如何使用它们实现集成测试,被这些测试依赖的对象可以是任意文件或任意类。

2. The @Resource Annotation @Resouece注解

The @Resource annotation is part of the JSR-250 annotation collection, and is packaged with Jakarta EE. This annotation has the following execution paths, listed by precedence:

@Resource注解是JSR-250注解集上的一员,和JakartaEE一起被打包发布。这个注解有三种工作方式,下面是通过优先级进行排序的结果

  1. Match by Name
  2. Match by Type
  3. Match by Qualifier

These execution paths are applicable to both setter and field injection.

这些注解搜索匹配模式,适用于set方法和字段的依赖注入。

2.1. Field Injection @Resource注解的字段依赖注入

We can resolve dependencies by field injection by annotating an instance variable with the @Resourceannotation.

可以通过字段注入来实现依赖注入,在一个实例变量上使用@Resource注解,来标记这个变量需要关联到一个bean对象即可。

2.1.1. Match by Name 通过名称Name搜索匹配依赖

We'll use the following integration test to demonstrate match-by-name field injection:

下面示例示范了@Resource的名称匹配模式

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class,classes=ApplicationContextTestResourceNameType.class)
public class FieldResourceInjectionIntegrationTest {@Resource(name="namedFile")private File defaultFile;@Testpublic void givenResourceAnnotation_WhenOnField_ThenDependencyValid(){assertNotNull(defaultFile);assertEquals("namedFile.txt", defaultFile.getName());}
}

Let's go through the code. In the FieldResourceInjectionTest integration test, at line 7, we resolved the dependency by name by passing in the bean name as an attribute value to the @Resource annotation:

浏览代码,在集成测试类 FieldResourceInjectionIntegrationTest 中,第7行,通过使用@Resource注解标明依赖对象的名称,来实现绑定并注入所需的依赖bean对象,代码如下:

@Resource(name="namedFile")
private File defaultFile;

This configuration will resolve dependencies using the match-by-name execution path. We must define the bean namedFile in the ApplicationContextTestResourceNameType application context.

这种配置,会使用名称匹配的模式来搜索关联所需依赖对象,所以,必须定义一个名为nameFile的对象,并放置到Spring的上下文环境中。

Note that the bean id and the corresponding reference attribute value must match:

必须注意的是,bean对象的id和引用属性的值(@Resource中的name)必须匹配

@Configuration
public class ApplicationContextTestResourceNameType {@Bean(name="namedFile")public File namedFile() {File namedFile = new File("namedFile.txt");return namedFile;}
}

If we fail to define the bean in the application context, it will result in an org.springframework.beans.factory.NoSuchBeanDefinitionException being thrown. We can demonstrate this by changing the attribute value passed into the @Bean annotation in the ApplicationContextTestResourceNameType application context, or changing the attribute value passed into the @Resource annotation in the FieldResourceInjectionTest integration test.

如果没能定义所需要的bean对象,就会抛出一个NoSuchBeanDefinitionException异常。可以通过修改属性的名称或者改变@Resource注解中的依赖对象名称来复现这一异常现象。

2.1.2. Match by Type 类型匹配

To demonstrate the match-by-type execution path, we just remove the attribute value at line 7 of the FieldResourceInjectionTest integration test:

为也演示类型配置模式,只需要去除@Resource注解中的属性即可,示例如下:

@Resource
private File defaultFile;

Then we run the test again. 再次运行测试类

The test will still pass because if the @Resource annotation doesn't receive a bean name as an attribute value, the Spring Framework will proceed with the next level of precedence, match-by-type, in order to try resolve the dependency.

如果@Resource注解没有指定依赖的bean名称作为参数,它仍然可以运行通过,因为Spring框架会使用下个优先处理模式来处理,即类型匹配来解决依赖查找。

2.1.3. Match by Qualifier 通过筛选模式匹配

To demonstrate the match-by-qualifier execution path, the integration testing scenario will be modified so that there are two beans defined in the ApplicationContextTestResourceQualifier application context:

为演示筛选匹配模式,测试用例将被修改,在程序上下文中定义两个同一类型的bean,如下

@Configuration
public class ApplicationContextTestResourceQualifier {@Bean(name="defaultFile")public File defaultFile() {File defaultFile = new File("defaultFile.txt");return defaultFile;}@Bean(name="namedFile")public File namedFile() {File namedFile = new File("namedFile.txt");return namedFile;}
}

We'll use the QualifierResourceInjectionTest integration test to demonstrate match-by-qualifier dependency resolution. In this scenario, a specific bean dependency needs to be injected into each reference variable:

下面将使用 QualifierResourceInjectionTest 这个测试类来演示筛选模式匹配模式来查找依赖。在这个场景下,指定的bean依赖对象需要被指定给每一个它的引用对象。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class,classes=ApplicationContextTestResourceQualifier.class)
public class QualifierResourceInjectionIntegrationTest {@Resourceprivate File dependency1;@Resourceprivate File dependency2;@Testpublic void givenResourceAnnotation_WhenField_ThenDependency1Valid(){assertNotNull(dependency1);assertEquals("defaultFile.txt", dependency1.getName());}@Testpublic void givenResourceQualifier_WhenField_ThenDependency2Valid(){assertNotNull(dependency2);assertEquals("namedFile.txt", dependency2.getName());}
}

When we run the integration test, an org.springframework.beans.factory.NoUniqueBeanDefinitionException will be thrown. This will happen because the application context will find two bean definitions of type File, and won't know which bean should resolve the dependency.

<

这篇关于Wiring in Spring: @Autowired, @Resource and @Inject 三种注解实现依赖注入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1022444

相关文章

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断