背景

在项目中使用Spring的Bean,一般都使用默认的Bean的单例,并且结合@Autowire使用。

实在有同一个类型多个实例的情况,也使用@Qualifier或@Resource实现注入。

所以,对@Autowire的注入规则并不是特别的清楚。

今天突然想起这个疑惑,就用简单的实验确认一下。

实验的基础类

AppleBean,里面有个字符串的属性,和覆盖toString方法,用于在打印日志里更明显地分辨不同的bean:

public class AppleBean {

    private String content;

    public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} @Override
public String toString() {
return "AppleBean{" +
"content='" + content + '\'' +
'}';
} }

当容器中该类型只有一个Bean实例时,按类型注入,与Bean名字无关

注册一个Bean,叫appleBean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class BeanConfig { @Bean
public AppleBean appleBean() {
AppleBean appleBean = new AppleBean();
appleBean.setContent("1");
return appleBean;
} }

将AppleBean注入到一个Controller中,并在此Controller的方法中打印AppleBean:

import com.example.demo.bean.AppleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HeartBeatController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private AppleBean appleBean; @GetMapping("/test")
public String test() {
this.logger.info("appleBean -> {}", appleBean);
return "SUCCESS";
} }

运行程序,并访问此测试接口,可见日志,appleBean成功注入:

com.example.demo.HeartBeatController     : appleBean -> AppleBean{content='1'}

修改注入的属性名为appleBean2,与注册的bean名字appleBean是不一致的哦:

import com.example.demo.bean.AppleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HeartBeatController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private AppleBean appleBean2; @GetMapping("/test")
public String test() {
this.logger.info("appleBean -> {}", appleBean2);
return "SUCCESS";
} }

再运行,日志如下,appleBean也正常注入进来了:

com.example.demo.HeartBeatController     : appleBean -> AppleBean{content='1'}

此节结论:

当容器中该类型只有一个Bean实例时,按类型注入,与Bean名字无关

当容器中该类型只有多个Bean实例时,按类型注入,与Bean名字有关

我们实例化两个AppleBean,名字分别为appleBean、appleBean2:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class BeanConfig { @Bean
public AppleBean appleBean() {
AppleBean appleBean = new AppleBean();
appleBean.setContent("1");
return appleBean;
} @Bean
public AppleBean appleBean2() {
AppleBean appleBean = new AppleBean();
appleBean.setContent("2");
return appleBean;
} }

我们注入appleBean2试试:

import com.example.demo.bean.AppleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HeartBeatController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private AppleBean appleBean2; @GetMapping("/test")
public String test() {
this.logger.info("appleBean -> {}", appleBean2);
return "SUCCESS";
} }

运行,可见日志,与名字精准匹配的Bean被注入进来:

com.example.demo.HeartBeatController     : appleBean -> AppleBean{content='2'}

我们注入appleBean3试试,appleBean3是一个不存在的Bean名字:

import com.example.demo.bean.AppleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HeartBeatController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private AppleBean appleBean3; @GetMapping("/test")
public String test() {
this.logger.info("appleBean -> {}", appleBean3);
return "SUCCESS";
} }

日志如下,启动时就报异常了:

Field appleBean3 in com.example.demo.HeartBeatController required a single bean, but 2 were found:
- appleBean: defined by method 'appleBean' in class path resource [com/example/demo/bean/BeanConfig.class]
- appleBean2: defined by method 'appleBean2' in class path resource [com/example/demo/bean/BeanConfig.class]

我们再实例化另一种类(BoyBean,不是刚才的AppleBean哦),但将它注册的Bean名叫appleBean3:

@Bean
public BoyBean appleBean3() {
BoyBean boyBean = new BoyBean();
return boyBean;
}

再运行,仍然报错,与上面的异常是一致的:

Field appleBean3 in com.example.demo.HeartBeatController required a single bean, but 2 were found:
- appleBean: defined by method 'appleBean' in class path resource [com/example/demo/bean/BeanConfig.class]
- appleBean2: defined by method 'appleBean2' in class path resource [com/example/demo/bean/BeanConfig.class]

此节结论:

当容器中该类型只有多个Bean实例时,按类型注入,与Bean名字有关

【Spring】Spring的@Autowire注入Bean的规则测试的更多相关文章

  1. Spring的几种注入bean的方式

    在Spring容器中为一个bean配置依赖注入有三种方式: · 使用属性的setter方法注入  这是最常用的方式: · 使用构造器注入: · 使用Filed注入(用于注解方式).   使用属性的se ...

  2. Spring IOC容器中注入bean

    一.基于schema格式的注入 1.基本的注入方式 (属性注入方式) 根据setXxx()方法进行依赖注入,Spring只会检查是否有setter方法,是否有对应的属性不做要求 <bean id ...

  3. Spring的DI(Ioc) - 注入bean 和 基本数据类型

    注入bean有两种方式: 注入其他bean: 方式一 <bean id="orderDao" class="cn.itcast.service.OrderDaoBe ...

  4. Spring中如何动态注入Bean实例教程

    前言 在Spring中提供了非常多的方式注入实例,但是由于在初始化顺序的不同,基于标注的注入方式,容易出现未被正确注入成功的情况. 本文将介绍一种在实际项目中基于动态的方式来提取Spring管理的Be ...

  5. Spring在Thread中注入Bean无效的解决方式

    在Spring项目中,有时需要新开线程完成一些复杂任务,而线程中可能需要注入一些服务.而通过Spring注入来管理和使用服务是较为合理的方式.但是若直接在Thread子类中通过注解方式注入Bean是无 ...

  6. 在servlet中用spring @Autowire注入Bean

    在servlet中新增init方法: public void init(ServletConfig config) { super.init(config); SpringBeanAutowiring ...

  7. Spring框架知识总结-注入Bean的各类异常

    近日整合sping和hibernate框架时遇到了一系列的异常,本次主要说明一下spring框架可能出现的异常及解决方案. 我们借助sping强大的bean容器管理机制,通过BeanFactory轻松 ...

  8. 解决Spring+Quartz无法自动注入bean问题

    问题 我们有时需要执行一些定时任务(如数据批处理),比较常用的技术框架有Spring + Quartz中.无奈此方式有个问题:Spring Bean无法自动注入. 环境:Spring3.2.2 + Q ...

  9. Spring 注解Autowired自动注入bean异常解决

      错误: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'xx' is defined ...

  10. Spring为IOC容器注入Bean的五种方式

    一 @Import导入组件,id默认是组件的全类名 //类中组件统一设置.满足当前条件,这个类中配置的所有bean注册才能生效: @Conditional({WindowsCondition.clas ...

随机推荐

  1. 【第2章】matlab程序设计基础

    matlab语言的常量与变量 matlab语言的变量命名规则 由一个字母引导,后面可以为其他字符. 区分大小写 如Abc ≠ ABc matlab的保留常量 以下为系统保留常量,自己定义的变量不能与他 ...

  2. C#/.NET/.NET Core技术前沿周刊 | 第 17 期(2024年12.09-12.15)

    前言 C#/.NET/.NET Core技术前沿周刊,你的每周技术指南针!记录.追踪C#/.NET/.NET Core领域.生态的每周最新.最实用.最有价值的技术文章.社区动态.优质项目和学习资源等. ...

  3. R数据分析:结合APA格式作图大法讲讲ggplot2和ggsci,请收藏

    之前给大家写过一篇plot的基础操作,相信同学们应该没有看过瘾.不过主流的用的多的还是ggplot2,所以今天打算结合一个形成APA样板格式图片的实例写写ggplot2的操作和图的配色. 关于APA格 ...

  4. 逍遥模拟器+Fiddler抓包 (附带软件)

    获取软件地址: 链接:https://pan.baidu.com/s/1zE9AECWOZlw_VDVMAnkBhQ?pwd=c0kq 提取码:c0kq 一.逍遥模拟器安装 1. 安装逍遥模拟器: 2 ...

  5. Quartz分布式定时任务

    前言: 项目需要执行定时任务,该类定时任务只需要实现类似Spring原生的@Scheudle注解的定时方法即可,无需考虑分片.刷新及重启,且因项目是多实例,所以需要考虑实现分布式,考察了目前开源的几款 ...

  6. 解决:The content of element type "web-app" must match "(icon?display

    错误描述: The content of element type "web-app" must match"(icon?,display-name?,descripti ...

  7. JVM实战—11.OOM的原因和模拟以及案例

    大纲 1.线上系统突然由于OOM内存溢出挂掉 2.什么是内存溢出及哪些区域会发生内存溢出 3.Metaspace如何因类太多而发生内存溢出 4.无限制调用方法如何让线程的栈内存溢出 5.对象太多导致堆 ...

  8. VSCode远程开发Linux内核驱动

    受够了Vim的换台电脑就要倒腾N天配置的折磨,受够了Windows下Source Insight眼花的界面.这些软件虽然很多人在用,但是缺点也不少.然而Linux内核代码非常庞大,编译内核又需要在Li ...

  9. 一问一答学习PyQT6,对比WxPython和PyQt6的差异

    在我的基于WxPython的跨平台框架完成后,对WxPython的灵活性以及强大功能有了很深的了解,在跨平台的桌面应用上我突然对PyQt6的开发也感兴趣,于是准备了开发环境学习PyQt 6,并对比下W ...

  10. java第二章数组学习

    java第二章数组 数组的概念和特点 数组(Array),是多个相同类型数据按一定顺序排列的集合,并使用一个 名字命名,并通过编号的方式对这些数据进行统一管理. 特点 数组本身是引用数据类型,而数组中 ...