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注解没有特殊限制

相关推荐
sunburn-21 分钟前
Java 队列全面详解:从入门到面试实战
java·开发语言·汇编·ide·idea
vx-程序开发1 小时前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
攻城有术1 小时前
专项攻克——spring、springMVC、springBoot、springCloud的启动流程
spring boot·spring·spring cloud
独行侠影a1 小时前
SpringBoot 分布式锁实战:Redisson 解决订单超卖并发问题
spring boot·分布式·后端
妙码生花1 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十八):后台系统配置管理实现
前端·后端·go
IT_陈寒2 小时前
Java并行流把我坑惨了:原来不是线程安全的!
前端·人工智能·后端
zzh___zzh2 小时前
SQL 窗口函数 ROW_NUMBER、RANK、DENSE_RANK 常用方法笔记
java
计科土狗2 小时前
GESP六级专题之类与对象
java·前端·数据库
Slow菜鸟3 小时前
第3篇:实操落地篇 · 3套企业标准工作流(IDEA可视化版)
java·ide·intellij-idea