背景

在项目中使用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. COSBrowser 文件对比——更实用的文件管理功能

    我们在使用 COSBrowser 来管理腾讯云存储的文件时,目前我们大家所熟知的上传/下载方式,主要有以下三种: 通过点击按钮上传/下载 通过拖拽的形式进行上传/下载 通过 URL 链接进行上传/下载 ...

  2. VB 不应该是这副模样出现

    和同时代的其它语言比,VB 设计的太烂了,应景之作,充满了各种小聪明. 当时有 JS, 有 python,VB 的设计者不懂参考借鉴,给出的是一个连继承都没有的设计. VB 的语言设计问题极多, 首选 ...

  3. 【Windows】查看笔记本电池寿命/损耗度(查看电池使用时间报告)

    ① Win+r 运行 命令提示符窗口 ② 输入powercfg/batteryreport 你将会得到电池使用时间报告 将这个地址粘贴到浏览器地址栏访问,或者根据这个地址在资源管理器中找到这个文件夹双 ...

  4. java 随机生成字符串 RandomStringUtils

    使用RandomStringUtils,可以选择生成随机字符串,可以是全字母.全数字或自定义生成字符等等... 其最基础的方法如下: public static String random(int c ...

  5. Qt编写安防视频监控系统54-轮询配置

    一.前言 视频监控系统中少不了用到视频轮询,按照设计的基本原则,先满足基本的用户需求,稳定跑起来,再去折腾更复杂的应用场景,于是本系统也做了个基本的视频轮询功能,可以设置轮询方案,给某个轮询方案设置轮 ...

  6. vue3 路由的使用

    添加一个router.js 配置文件 import { createRouter, createWebHistory } from 'vue-router' createRouter:用来创建 路由 ...

  7. CDS标准视图:设备信息 I_EquipmentData

    视图名称:I_EquipmentData 视图类型:基础视图 视图代码: 点击查看代码 @EndUserText.label: 'Equipment Data' @VDM.viewType: #COM ...

  8. tomcat常用配置详解和优化方法-copy

    tomcat常用配置详解和优化方法 参考: http://blog.csdn.net/zj52hm/article/details/51980194 http://blog.csdn.net/wuli ...

  9. JVM监控工具使用

    1. 描述 ​ 程序在开发过程中,有可能会发生CPU飙高.内存溢出等问题或系统在后期调优阶段,不可避免的要监控JVM情况,JDK自带的Jconsole监控工具,结合Tomcat使用非常方便,占用内存小 ...

  10. SSH 框架的搭建

    Structs1+spring+Hibernate Structs  相当于mvc设计模式中V.C,即jsp页面和Servlet: spring 管理业务逻辑,即Service: Hibernate ...