@Autowrited和@Resource注解的区别及使用场景

简介

@Autowrited、@Resource,是 Spring Boot 项目中,装配 Bean 对象的两个注解,都可以将 IOC 容器中的取出来使用。

本文介绍 @Autowrited 和 @Resource 注解的区别及使用场景。

区别

如下

特性 @Autowired @Resource
来源 Spring JDK
默认注入策略 按类型 按名称
是否可指定必须 可指定(required=false) 不可
支持的注入方式 构造器、属性 属性(不支持构造器)
另外 可以配合 @Qualifier 指定装配 Bean 无额外配合使用的注解

使用场景

大多数情况,随便用,看项目中大多数是用哪个就用哪个,如下,

java 复制代码
    @Autowired
    private Service3 service3;

    @Resource
    private OrderService orderService;

在 Spring Boot 中,代码规范推荐,@Autowired 推荐使用构造器注入,而不是属性注入

@Autowired 推荐这么用

java 复制代码
    private OrderService orderService;

    @Autowired
    public DemoController(OrderService orderService) {
        this.orderService = orderService;
    }

如果项目中有多个类型的 Bean,@Resource,需要在属性里指定使用哪个,如下:

java 复制代码
    @Resource(name = "service3Impl2")
    private Service3 service3;

@Autowired 也需要,只不过不是在这个注解里指定,可以配合 @Qualifier、@Primary,如下:

java 复制代码
    @Autowired
    @Qualifier("service3Impl2")
    private Service3 service3;

或者在某个实现类上,加 @Primary,表示多个 Bean,没有指定就用我,我是主要的。

java 复制代码
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

@Service
@Primary
public class Service3Impl implements Service3 {
}

综上,使用上区别很小,主要是 IOC 中有多个相同 Bean 时的解决方案。

相关推荐
饮水桶_T8 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
她的男孩8 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
炸膛坦客9 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
咖啡八杯9 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
拖孩10 小时前
又又又用 AI 写了个小程序:我站起来猛蹬 AI,使劲薅羊毛
前端·后端·微信小程序
bufengwangluo10 小时前
企业上网行为管理:代理网关部署位置怎么选,策略怎么落
开发语言·php
北冥有鱼10 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger11 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
Sailing11 小时前
🔥🔥sql: waiting for connection 踩坑:不要一味调大 MaxOpenConns
后端·go·gin
饮水桶_T12 小时前
HashMap笔记
开发语言·数据结构·笔记