【Spring】Spring的@Autowire注入Bean的规则测试

本文通过实验探讨了Spring框架中@Autowired注解的注入规则。当容器内Bean的类型唯一时,按类型注入与Bean名称无关;当存在多个相同类型的Bean时,必须指定名称(如@Qualifier或@Resource)进行精确匹配。实验展示了当尝试注入不存在的Bean名称时,Spring会抛出异常。结论强调了在多Bean情况下,按名称注入的重要性。
摘要由CSDN通过智能技术生成

背景

在项目中使用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名字有关

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值