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;

    @Test
    public 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 {

    @Resource
    private File dependency1;
	
    @Resource
    private File dependency2;

    @Test
    public void givenResourceAnnotation_WhenField_ThenDependency1Valid(){
        assertNotNull(dependency1);
        assertEquals("defaultFile.txt", dependency1.getName());
    }

    @Test
    public 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.

<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值