Spring中@Autowired@Resource和@Inject注解区别

首先说明ByType和ByName的区别:

ByType也就是当spring容器中只有一个Bean时,才会使用ByType,否则会报错

byName:根据属性名称来匹配Bean的名称进行自动装配。

@Autowired:来源于spring框架自身默认是byType自动装配,当配合了@Qualifier注解之后,

由@Qualifier实现byName装配。它有一个required属性,用于指定是否必须注入成功,默认为true。

java 复制代码
package com.spring.service.impl;

import com.spring.dao.AccountDao;
import com.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    @Qualifier("accountDaoImplTwo")
    private AccountDao accountDao;
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
java 复制代码
package com.spring.dao.impl;

import com.spring.dao.AccountDao;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDaoImplOne implements AccountDao {
    @Override
    public void saveAccount() {
        System.out.println("one保存了账户信息");
    }
}
java 复制代码
package com.spring.dao.impl;

import com.spring.dao.AccountDao;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDaoImplTwo implements AccountDao {
    @Override
    public void saveAccount() {
        System.out.println("two保存了账户信息");
    }
}

测试类

java 复制代码
import com.spring.service.AccountService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext("com.spring");
        AccountService accountService = ac.getBean("accountService",AccountService.class);
        accountService.saveAccount();

    }
}

调试结果

@Resource:在没有指定name属性时是byType自动装配,当指定了name属性之后,采用byName方式自动装配。

@Inject:可以配合@Qualifier或者@Primary注解使用。默认是采用byType装配,当指定@Named注解之后,变成byName装配。属性:无使用场景

在使用@Autowired注解的地方,都可以替换成@Inject。它也可以出现在方法上,构造函数上和字段上

@Autowired注解时spring的ioc容器中的特有注解,只能在spring框架中使用,但是@Inject注解没有特殊限制

相关推荐
IT_陈寒15 分钟前
React的状态更新坑得我差点加班到天亮
前端·人工智能·后端
渡我白衣38 分钟前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
电商API_1800790524742 分钟前
电商商品价格监控工具淘宝京东商品价格抓取API项目实操分享
java·大数据·开发语言·前端·数据挖掘
zzzll111143 分钟前
深度剖析:HashMap 并发死循环与 ConcurrentHashMap 两代演进全解
java·开发语言
秋名RG1 小时前
2026/5/27 生产事故复盘与整改方案
java
码事漫谈1 小时前
一天搭出 80% 的 Agent,然后卡在 95% 到死
后端
leonkay1 小时前
C# 锁机制——【2】深入原理
开发语言·后端·spring·c#·个人开发
血小板要健康2 小时前
链表 阶段算法总结
java·数据结构·笔记·算法·leetcode·链表
江湖十年2 小时前
在 Go 中使用 dyno 包处理动态对象
后端·面试·go
坐吃山猪2 小时前
【多线程】CompletableFuture使用
java·开发语言·多线程