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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.