聊聊依赖注入注解@Resource和@Autowired

1. 前言

@Resource@Autowired注解均可以在Spring Framework应用中进行声明式的依赖注入。并且面试中常常涉及到这两个注解的知识点。今天咱们来总结一下它们。html

2. @Resource

全称javax.annotation.Resource,它属于JSR-250规范的一个注解,包含Jakarta EEJ2EE)中。Spring提供了对该注解的支持。咱们来详细了解一下该注解的规则。java

该注解使用在成员属性和setter方法上。默认状况下@Resource按照名称注入,若是没有显式声明名称则按照变量名称或者方法中对应的参数名称进行注入。面试

Resource注解流程

若是咱们但愿在目标Bean中体现多态咱们能够这样写:spring

/**
 * 多态的体现.
 *
 * @author felord.cn
 * @since 9 :26
 */
@Component
public class ResourceTest {
    @Resource
    private ApplicationRunner applicationRunner;    
    @Resource
    private ApplicationRunner runner;
    // ...
}
Qualifier 约束参见 Spring 注解 @Qualifier 详细解析

3. @Autowired

@Autowired一般适用于构造函数,成员变量以及方法上。它的机制是这样的:数组

Autowired流程

这个注解咱们是须要好好聊聊的,平常使用频率至关高。app

3.1 标注在构造上

经过在目标Bean的构造函数上标注就能够注入对应的Bean函数

package cn.felord;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author felord.cn
 * @since 9:26
 **/
@Component
public class AutowiredTest {
 private final ApplicationRunner applicationRunner;

    @Autowired
    public AutowiredTest(ApplicationRunner applicationRunner) {
        this.applicationRunner = applicationRunner;
    }
}
Spring Framework 4.3开始, @Autowired若是目标Bean只定义一个构造函数,则再也不须要在该构造函数上添加 @Autowired注解。若是目标Bean有几个构造函数可用,而且没有主/默认构造函数,则必须至少有一个构造函数被 @Autowired标记,以指示Spring IoC容器使用哪一个构造函数。

3.2 标注在成员变量上

@Resource同样,@Autowired也能够标注到目标Bean的成员变量上。ui

/**
 * @author felord.cn
 * @since 9:26
 **/
@Component
public class AutowiredTest {
    @Autowired
    private ApplicationRunner applicationRunner;
    
    // ...
    
}

3.3 标注到方法上

通常setter方法上使用的比较多。并且一个 @Autowired 支持注入多个参数。this

/**
 * The type Autowired test.
 *
 * @author felord.cn
 * @since 9 :26
 */
@Component
public class AutowiredTest {

    private ApplicationRunner applicationRunner;
    private EmployeeMapper employeeMapper;
    private DepartmentMapper departmentMapper;

    /**
     * Sets application runner.
     *
     * @param applicationRunner the application runner
     */
    @Autowired
    public void setApplicationRunner(ApplicationRunner applicationRunner) {
        this.applicationRunner = applicationRunner;
    }


    /**
     * 支持多参数
     *
     * @param employeeMapper   the employee mapper
     * @param departmentMapper the department mapper
     */
    @Autowired
    public void prepare(EmployeeMapper employeeMapper, DepartmentMapper departmentMapper) {
        this.employeeMapper = employeeMapper;
        this.departmentMapper = departmentMapper;
    }

}

你觉得这就完了?下面这种方式估计大多数人并无在乎过。spa

/**
 * The type Autowired test.
 *
 * @author felord.cn
 * @since 9 :26
 */
@Component
public class AutowiredTest {
    // 注入 数组
    @Autowired
    private MovieCatalog[] movieCatalogs;
    
    private Map<String, Movie> movies;
    
    private Set<CustomerPreferenceDao> customerPreferenceDaos;
    
    // 注入 set
    @Autowired
    public MovieRecommender(Set<CustomerPreferenceDao> customerPreferenceDaos) {
        this.customerPreferenceDaos = customerPreferenceDaos;
    }
            
    // 注入 map 
    @Autowired
    public void setMovieCatalogs(Map<String, Movie> movies) {
        this.movies = movies;
    }
   
    // ...
}

能够把Bean注入目标Bean的数组、集合容器中去。默认状况下,当给定注入点没有匹配的候选Bean可用时,自动装配将失败。至少应有一个匹配元素。

若是您但愿元素按照特定顺序排序,则元素Bean能够实现 org.springframework.core.Ordered接口或者对应注解 @Order或标准 @Priority。基于某些机制不建议使用注解方式来排序,不然没法达到预期指望,推荐使用接口 Ordered

3.4 装配可选

@Resource没有提供可选择装配的特性,一旦没法装配则会抛出异常;而@Autowired提供了required属性(默认值为true)以免这种状况,设置@Autowiredfalse

/**
 * The type Autowired test.
 *
 * @author felord.cn
 * @since 9 :26
 */
@Component
public class AutowiredTest {
    // 一旦找不到 movieFinder  不会异常  而初始化为 null
    @Autowired(required = false)
    private MovieFinder movieFinder;
    // ...
}

这里也有骚操做,你能够忽略required属性。经过 Java 8java.util.Optional来代表候选Bean可选。

/**
 * The type Autowired test.
 *
 * @author felord.cn
 * @since 9 :26
 */
@Component
public class AutowiredTest {
public class SimpleMovieLister {
    // 使用 Optional 代表候选Bean可选
    @Autowired
    public void setMovieFinder(Optional<MovieFinder> movieFinder) {
     //   ...
    }
}

Spring 5.0开始,您还可使用@Nullable注解,这个注解能够你本身实现检测逻辑或者直接使用 JSR-305提供的javax.annotation.Nullable

/**
 * The type Autowired test.
 *
 * @author felord.cn
 * @since 9 :26
 */
@Component
public class AutowiredTest {
public class SimpleMovieLister {
    // 使用 @Nullable 注解代表候选Bean可选
    @Autowired
    public void setMovieFinder(@Nullable MovieFinder movieFinder) {
      //  ...
    }
}

4. @Inject

Spring 3.0开始,Spring提供对JSR-330标准注解(依赖注入)的支持。 你须要引入依赖:

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

而后你就可使用相关的注解来进行依赖注入了,其中主要注解为@javax.inject.Inject。大部分状况下该注解均可以代替@Autowired使用,但@Inject没有required属性,不过它也能够与java.util.Optional或使用@Nullable来达到一样的效果。

大部分状况下没有人喜欢额外引入 Jakarta EE依赖来使用一个已经拥有的功能, Spring堵死了 Jakarta EE依赖注入的生态。

5. 总结

@Resource@Autowired的优先级顺序不一样(参见上图),另外@Resource属于 Jakarta EE规范而@Autowired属于Spring范畴,@Resource没法使用在构造参数中,@Autowired支持required属性。从面向对象来讲,@Resource更加适用于多态性的细粒度注入,而@Autowired更多专一于多态的单例注入。@Inject 则不必过多讨论,只做为一个添头。好了今天就到这里,多多关注:码农小胖哥,更多干货知识分享。

关注公众号:Felordcn 获取更多资讯

我的博客:https://felord.cn

相关文章
相关标签/搜索