@Autowired和@Resource的使用

本文深入解析了Spring框架中@Autowired和@Resource注解的使用方法及差异。详细介绍了@Autowired通过byType进行依赖查找,以及@Resource默认通过byName进行bean查找的机制。同时,探讨了在特定情况下如何选择使用这两个注解。

一. @Autowired注解

 源码:

Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to {@code true}.
	 */
	boolean required() default true;

}

可以看到其中只有一个属性可以选择 required,这个属性代表,我们容器启动时候是否必须进行值加载给对应的属性,对于这个注解是通过byType注入的,意思就是我们容器如果存在类型和当前属性一样,将会将容器中的该bean赋值给被@Autowired修饰的属性,如果存在多个类型匹配,请在需要被注入的bean上加@Primary进行标识,具体可以参考:AutowiredAnnotationBeanPostProcessor 源码

二. @Resource注解

源码:

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
    
    /**
     * The JNDI name of the resource.  For field annotations,
     * the default is the field name.  For method annotations,
     * the default is the JavaBeans property name corresponding
     * to the method.  For class annotations, there is no default
     * and this must be specified.
     */
    String name() default "";

     /**
     * The JNDI name of the resource.  For field annotations,
     * the default is the field name.  For method annotations,
     * the default is the JavaBeans property name corresponding
     * to the method.  For class annotations, there is no default
     * and this must be specified.
     */
    Class<?> type() default java.lang.Object.class;

}

这个注解主要是默认通过byName进行bean查找,意思就是如果查找到我们指定的别名和这个容器中的名字存在相同,而且能够被正常赋值,那么可以就查找成功,如果没有查到,我们将通过byType进行查找,具体源码,可以参考CommonAnnotationBeanPostProcessor 源码

总结:一般我们使用@Autowired和@Resource基本没有咋分,有时候可能会遇到我们@Autowired出错情况,要不就是找不到bean,或者bean超过一个,这个时候@Resource我们通过指定名字注入就能避免部分问题,所以使用根据情况选择。

### Spring 中 `@Autowired` 与 `@Resource` 的区别及其使用场景 #### 主要区别 1. **来源不同** - `@Autowired` 是由 Spring 提供的注解,主要用于 Spring 容器中的依赖注入[^1]。 - `@Resource` 则是由 JDK 提供的标准注解,遵循 JSR-250 规范,适用于任何支持该规范的 Java 容器[^4]。 2. **默认注入方式** - `@Autowired` 默认按照类型 (`ByType`) 进行匹配并完成 Bean 的注入。如果存在多个相同类型的 Bean,则会抛出异常。 - `@Resource` 默认按照名称 (`ByName`) 进行匹配。如果没有找到对应的名称,则退而求其次按类型进行匹配。 3. **解决多实现类的情况** - 当一个接口有多个实现类时: - 对于 `@Autowired`,可以配合 `@Qualifier` 明确指定需要注入的具体 Bean 名称。 - 而对于 `@Resource`,可以直接通过其属性 `name` 来显式指定目标 Bean 的名称。 4. **灵活性与控制力** - 在 Spring 应用开发中,推荐优先使用 `@Autowired`,因为它更加贴合 Spring 的设计理念,并提供诸如懒加载(`lazy-init=true`)以及更精细的错误处理机制等功能[^2]。 #### 使用场景分析 - 如果项目完全基于 Spring 或者主要采用 Spring 技术栈构建,则应首选 `@Autowired` 实现依赖注入操作。 - 若处于混合技术环境或者希望保持代码独立性(不绑定特定框架),那么可以选择更为通用的 `@Resource` 注解。 ```java // 示例:使用 @Autowired 配合 @Qualifier 处理多实现情况 @Component public class ExampleService { @Autowired @Qualifier("specificImplementation") private MyInterface myInstance; } // 示例:使用 @Resource 指定具体 bean name @Component public class AnotherExampleService { @Resource(name="anotherSpecificImplementation") private MyInterface anotherMyInstance; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值