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

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus