背景

在项目中使用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. C#向JAVA发送form-data文件问题处理方案

    前言 和上一篇文章一样,.NET 和 JAVA之间的接口请求又遇到了新问题 我们有一个用来接收文件的接口,外部把文件流.文件名.目录,传进来,我们系统把生成的附件ID反回去,接口为POST-form- ...

  2. Gitlab的备份与恢复,异机转移

    ​注意:异机转移的时候,gitlab的版本必须一致. 一.备份GitLab数据 停止GitLab服务 gitlab-ctl stop unicorn gitlab-ctl stop sidekiq 创 ...

  3. ECShop开源商城与COS互通:降低本地存储负载、提升访问体验

    ECShop简介 ECShop是一款开源电子商务平台,具有简单易用.安全稳定.模块化设计等特点.它提供了完整的电子商务解决方案,包括商品管理.订单管理.支付管理.配送管理.会员管理.促销管理.数据统计 ...

  4. GraphQL Part V: 字段,参数和变量

    字段 我们对字段已经有了好的起点,我们在 HelloWorldQuery 中有两个字段:hello 和 world.他们都是单值字段. 现在我们可以扩展应用来支持复杂类型.例如,我们想象一下,我们在创 ...

  5. 如何设置AD域用户仅登录到指定的计算机?AD域管理软件

    一 什么是AD域? 简单理解:Active Directory域内的directory database(目录数据库)是被用来存储用户账户.计算机账户.打印机和共享文件夹等对象,而提供目录服务的组件就 ...

  6. Qt开源作品42-视频监控布局

    一.前言 自从做监控系统以来,就一直有打算将这个功能独立出来一个类,这样的话很多系统用到此类布局切换,通用这个类就行,而且后期此布局会增加其他异形布局,甚至按照16:9之类的比例生成布局,之前此功能直 ...

  7. 如何在众多Ubuntu版本中挑选出最适配自身需求的系统版本?用德承工控机GM-1100来深度剖析其中的门道

    Ubuntu是一款基于Debian GNU/Linux,支持x86.amd64(x64)和ppc架构,以桌面应用为主的Linux操作系统.其名称来自非洲南部的语言"ubuntu"( ...

  8. Diffusion Model-Stable Diffusion(一)

    Stable Diffusion 是一个基于扩散模型的图像生成模型,可以用于生成高质量图像.其传统实现主要基于 PyTorch,最常用的开源实现是 CompVis/stable-diffusion 和 ...

  9. 23种设计模式实战:重学Java设计模式

    23种设计模式实战PDF: 链接:https://pan.baidu.com/s/1XfjkBt19G7jZQfwk5wAV3w 提取码:1234

  10. 即时通讯技术文集(第23期):IM安全相关文章(Part12) [共15篇]

    为了更好地分类阅读 52im.net 总计1000多篇精编文章,我将在每周三推送新的一期技术文集,本次是第23 期. [- 1 -] 理论联系实际:一套典型的IM通信协议设计详解(含安全层设计) [链 ...