@Autowird 注解与存在多个相同类型对象的解方案

news2025/4/18 22:45:18

现有一个 Student 类,里面有两个属性,分别为 name 和 id;有一个 StuService 类,里面有两个方法,返回值均为类型为 Student 的对象;还有一个 StuController 类,里面有一个 Student 类型的属性,还有一个打印这个属性的方法。代码如下:

Student 类:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
    private String name;
    private Integer id;
}

StuService 类:

@Service
public class StuService {

    @Bean
    public Student s1() {
        return new Student("zhangsan", 12);
    }

    @Bean
    public Student s2() {
        return new Student("lisi", 14);
    }
}

StuController 类:

@Controller
public class StuController {

    //属性注入
    @Autowired
    public Student student;

    public void print() {
        System.out.println(student);
    }
}

启动类:

@SpringBootApplication
public class SpringBootDemo2025417Application {

	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(SpringBootDemo2025417Application.class, args);

		//获取 StuController 对象
		StuController stuController = context.getBean(StuController.class);
		stuController.print();
	}

}

代码运行结果如下:

Description:

Field student in com.gjm.demo.controller.StuController required a single bean, but 2 were found:
	- s1: defined by method 's1' in class path resource [com/gjm/demo/component/StuComponent.class]
	- s2: defined by method 's2' in class path resource [com/gjm/demo/component/StuComponent.class]

报错了,错误信息里说只需要一个对象,但却找到了两个。这就是我们在 StuService 中定义的两个方法,这两个方法均返回了 Student 类型的对象,就会造成 Spring 不知道需要使用哪个对象完成属性注入。

有三种解决方法,下面一一说明。

第一种方法,使用 @Qualifier 注解。在 @Autowired 注解上加上 @Qualifier 注解,表明需要注入的是哪个对象,代码如下:

@Controller
public class StuController {

    //属性注入
    @Qualifier("s1")
    @Autowired
    public Student student;

    public void print() {
        System.out.println(student);
    }
}

在这里选择了 s1 进行注入,运行结果如下:

结果显示的是 s1 返回的对象,名为 zhangsan。

第二种解决方案为使用 @Resource 注解,代码如下:

@Controller
public class StuController {

    @Resource(name = "s2")
    private Student student;

    public void print() {
        System.out.println(student);
    }
}

 在这里选择 s2 进行注入,运行结果如下:

第三种解决方案就是使用 @Primary 注解,代码如下:

@Service
public class StuService {

    @Primary
    @Bean
    public Student s1() {
        return new Student("zhangsan", 12);
    }

    @Bean
    public Student s2() {
        return new Student("lisi", 14);
    }
}

 @Primary 注解用途为将 s1 作为 Student 类的默认注入对象,这样就会优先选择 s1 进行属性注入,运行结果如下:

补充

@Qualifier 在传参的时候也可以指定默认的参数。现有下面代码:

Student 类:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
    private String name;
    private Integer id;
}

StuService 类:

@Service
public class StuService {

    @Bean
    public String name1() {
        return "zhangsan111";
    }

    @Bean
    public String name2() {
        return "zhangsan222";
    }


    @Bean
    public Student s1(String name) {
        return new Student(name, 12);
    }

    @Bean
    public Student s2() {
        return new Student("lisi", 14);
    }
}

StuController 类:

@Controller
public class StuController {

    @Resource(name = "s1")
    private Student student;

    public void print() {
        System.out.println(student);
    }
}

SpringBoot 启动类:

@SpringBootApplication
public class SpringBootDemo2025417Application {

	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(SpringBootDemo2025417Application.class, args);

		//获取 StuController 对象
		StuController stuController = context.getBean(StuController.class);
		stuController.print();
	}

}

代码运行结果如下:

Description:

Parameter 0 of method s1 in com.gjm.demo.service.StuService required a single bean, but 2 were found:
	- name1: defined by method 'name1' in class path resource [com/gjm/demo/service/StuService.class]
	- name2: defined by method 'name2' in class path resource [com/gjm/demo/service/StuService.class]

报错了,错误信息里说 s1 只需要一个参数,但却找到了两个。这时因为我们向 Spring 容器中注入了两个类型为 String 的对象,当 Spring 为 String 类型的参数赋值时,会在 Spring 容器中查找类型为 String 的对象。现在容器中有两个对象,Spring 不清楚到底需要使用哪一个。这时就需要我们手动指定 Spring 默认使用的参数了,即在参数前使用 @Qualiier 注解,代码如下:

    @Bean
    public Student s1(@Qualifier("name1") String name) {
        return new Student(name, 12);
    }

这时 name 参数拿到的就是 name1 返回的结果了,运行结果如下:

@Autowired 与 @Resource 的区别 

1、@Autowired 是 Spring 框架提供的注解,@Resource 是 JDK 提供的注解;

2、@Autowired 是按照类型注入的,@Resource 是按照名称注入的,@Resource 支持更多的参数设置。但严谨点说,@Resource 是按照类型 + 名称注入的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2337585.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

WordPiece 详解与示例

WordPiece详解 1. 定义与背景 WordPiece 是一种子词分词算法,由谷歌于2012年提出,最初用于语音搜索系统,后广泛应用于机器翻译和BERT等预训练模型。其核心思想是将单词拆分为更小的子词单元(如词根、前缀/后缀),从而解决传统分词方法面临的词汇表过大和未知词(OOV)处…

PVE+CEPH+HA部署搭建测试

一、基本概念介绍 Proxmox VE ‌Proxmox Virtual Environment (Proxmox VE)‌ 是一款开源的虚拟化管理平台,基于 Debian Linux 开发,支持虚拟机和容器的混合部署。它提供基于 Web 的集中管理界面,简化了计算、存储和网络资源的配置与监控。P…

ROS ROS2 机器人深度相机激光雷达多传感器标定工具箱

系列文章目录 目录 系列文章目录 前言 三、标定目标 3.1 使用自定义标定目标 四、数据处理 4.1 相机数据中的标定目标检测 4.2 激光雷达数据中的标定目标检测 输入过滤器: 正常估算: 区域增长: 尺寸过滤器: RANSAC&a…

android rtsp 拉流h264 h265,解码nv12转码nv21耗时卡顿问题及ffmpeg优化

一、 背景介绍及问题概述 项目需求需要在rk3568开发板上面,通过rtsp协议拉流的形式获取摄像头预览,然后进行人脸识别 姿态识别等后续其它操作。由于rtsp协议一般使用h.264 h265视频编码格式(也叫 AVC 和 HEVC)是不能直接用于后续处…

熊海cms代码审计

目录 sql注入 1. admin/files/login.php 2. admin/files/columnlist.php 3. admin/files/editcolumn.php 4. admin/files/editlink.php 5. admin/files/editsoft.php 6. admin/files/editwz.php 7. admin/files/linklist.php 8. files/software.php 9. files…

DeepSeek 与开源:肥沃土壤孕育 AI 硕果

当 DeepSeek 以低成本推理、多模态能力惊艳全球时,人们惊叹于国产AI技术的「爆发力」,却鲜少有人追问:这份爆发力的根基何在? 答案,藏在中国开源生态二十余年的积淀中。 从倪光南院士呼吁「以开源打破垄断」&#xf…

Maven中clean、compil等操作介绍和Pom.xml中各个标签介绍

文章目录 前言Maven常用命令1.clean2.vaildate3.compile4.test5.package6.verify7.install8.site9.deploy pom.xml标签详解格式<?xml version"1.0" encoding"UTF-8"?>(xml版本和编码)modelVersion&#xff08;xml版本&#xff09;groupId&#xff…

力扣刷题-热题100题-第35题(c++、python)

146. LRU 缓存 - 力扣&#xff08;LeetCode&#xff09;https://leetcode.cn/problems/lru-cache/?envTypestudy-plan-v2&envIdtop-100-liked 双向链表哈希表 内置函数 对于c有list可以充当双向链表&#xff0c;unordered_map充当哈希表&#xff1b;python有OrderedDic…

Nautilus 正式发布:为 Sui 带来可验证的链下隐私计算

作为 Sui 安全工具包中的强大新成员&#xff0c;Nautilus 现已上线 Sui 测试网。它专为 Web3 开发者打造&#xff0c;支持保密且可验证的链下计算。Nautilus 应用运行于开发者自主管理的可信执行环境&#xff08;Trusted Execution Environment&#xff0c;TEE&#xff09;中&a…

云服务器CVM标准型S5实例性能测评——2025腾讯云

腾讯云服务器CVM标准型S5实例具有稳定的计算性能&#xff0c;CPU采用采用 Intel Xeon Cascade Lake 或者 Intel Xeon Cooper Lake 处理器&#xff0c;主频2.5GHz&#xff0c;睿频3.1GHz&#xff0c;CPU内存配置2核2G、2核4G、4核8G、8核16G等配置&#xff0c;公网带宽可选1M、3…

leetcode面试经典算法题——2

链接&#xff1a;https://leetcode.cn/studyplan/top-interview-150/ 20. 有效的括号 给定一个只包括 ‘(’&#xff0c;‘)’&#xff0c;‘{’&#xff0c;‘}’&#xff0c;‘[’&#xff0c;‘]’ 的字符串 s &#xff0c;判断字符串是否有效。 有效字符串需满足&#x…

Ubuntu20.04安装企业微信

建议先去企业微信官网看一下有没有linux版本&#xff0c;没有的话在按如下方式安装&#xff0c;不过现在是没有的。 方案 1、使用docker容器 2、使用deepin-wine 3、使用星火应用商店 4. 使用星火包deepin-wine 5、使用ukylin-wine 本人对docker不太熟悉&#xff0c;现…

在Ubuntu服务器上部署xinference

一、拉取镜像 docker pull xprobe/xinference:latest二、启动容器&#xff08;GPU&#xff09; docker run -d --name xinference -e XINFERENCE_MODEL_SRCmodelscope -p 9997:9997 --gpus all xprobe/xinference:latest xinference-local -H 0.0.0.0 # 启动一个新的Docker容…

异步编程——微信小程序

1. 前言 引用来自&#xff1a;微信小程序开发中的多线程处理与异步编程_微信小程序 多线程-CSDN博客 微信小程序是基于JavaScript开发的&#xff0c;与浏览器JavaScript不同&#xff0c;小程序运行在WebView内部&#xff0c;没有多线程的概念。小程序的 JavaScript 是单线程的…

STM32 四足机器人常见问题汇总

文章不介绍具体参数&#xff0c;有需求可去网上搜索。 特别声明&#xff1a;不论年龄&#xff0c;不看学历。既然你对这个领域的东西感兴趣&#xff0c;就应该不断培养自己提出问题、思考问题、探索答案的能力。 提出问题&#xff1a;提出问题时&#xff0c;应说明是哪款产品&a…

Windows 下实现 PHP 多版本动态切换管理(适配 phpStudy)+ 一键切换工具源码分享

&#x1f680; Windows 下实现 PHP 多版本动态切换管理&#xff08;适配 phpStudy&#xff09; 一键切换工具源码分享 &#x1f4e6; 工具特点&#x1f9ea; 效果展示&#x1f9f1; 环境要求&#x1f9d1;‍&#x1f4bb; 源码展示&#xff1a;php_switcher.py&#x1f6e0; 打…

ReportLab 导出 PDF(图文表格)

ReportLab 导出 PDF&#xff08;文档创建&#xff09; ReportLab 导出 PDF&#xff08;页面布局&#xff09; ReportLab 导出 PDF&#xff08;图文表格) 文章目录 1. Paragraph&#xff08;段落&#xff09;2. Table&#xff08;表格&#xff09;3. VerticalBarChart&#xff0…

yolov8复现

Yolov8的复现流程主要包含环境配置、下载源码和验证环境三大步骤&#xff1a; 环境配置 查看电脑状况&#xff1a;通过任务管理器查看电脑是否有独立显卡&#xff08;NVIDIA卡&#xff09;。若有&#xff0c;后续可安装GPU版本的pytorch以加速训练&#xff1b;若没有&#xff0…

RestSharp和Newtonsoft.Json结合发送和解析http

1.下载RestSharp和Newtonsoft.Json 2编写ApiRequest和ApiResponse和调用工具类HttpRestClient 请求模型 /// <summary>/// 请求模型/// </summary>public class ApiRequest{/// <summary>/// 请求地址/api路由地址/// </summary>public string Route {…

【Pytorch之一】--torch.stack()方法详解

torch.stack方法详解 pytorch官网注释 Parameters tensors&#xff1a;张量序列&#xff0c;也就是要进行stack操作的对象们&#xff0c;可以有很多个张量。 dim&#xff1a;按照dim的方式对这些张量进行stack操作&#xff0c;也就是你要按照哪种堆叠方式对张量进行堆叠。dim的…