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

相关推荐
程序猿零零漆1 分钟前
飞算JavaAI:革新Java开发的智能助手
java·飞算javaai
万能小锦鲤13 分钟前
《Java EE与中间件》实验三 基于Spring Boot框架的购物车
java·spring boot·mysql·实验报告·购物车·文档资源·java ee与中间件
麦兜*26 分钟前
【Spring Boot】Spring Boot 4.0 的颠覆性AI特性全景解析,结合智能编码实战案例、底层架构革新及Prompt工程手册
java·人工智能·spring boot·后端·spring·架构
江南一点雨26 分钟前
ChatGPT,从规则到强化学习
后端
用户92724725021929 分钟前
实现新闻自动采集并发布到博客
后端
野犬寒鸦34 分钟前
MyBatis-Plus 中使用 Wrapper 自定义 SQL
java·数据库·后端·sql·mybatis
expect7g41 分钟前
Java的DNS缓存问题
java·后端
oioihoii42 分钟前
C++11中的std::minmax与std::minmax_element:原理解析与实战
java·开发语言·c++
karry01301 小时前
高并发导致重复key问题--org.springframework.dao.DuplicateKeyException
java·数据库·ide
全栈凯哥1 小时前
20.缓存问题与解决方案详解教程
java·spring boot·redis·后端·缓存