首页 > 开发 > Java > 正文

详解Spring @Autowired 注入小技巧

2024-07-14 08:41:48
字体:
来源:转载
供稿:网友

今天和同事讨论到Spring自动注入时,发现有这么一段代码特别地困惑,当然大致的原理还是可以理解的,只不过以前从来没有这么用过。想到未来可能会用到,或者未来看别人写的代码时不至于花时间解决同样的困惑,所以小编还是觉得有必要研究记录一下。

一、同一类型注入多次为同一实例

首先让我们先看下这段代码是什么?

@Autowiredprivate XiaoMing xiaoming;@Autowiredprivate XiaoMing wanger;

XiaoMing.java

package com.example.demo.beans.impl;import org.springframework.stereotype.Service;/** *  * The class XiaoMing. * * Description:小明 * * @author: huangjiawei * @since: 2018年7月23日 * @version: $Revision$ $Date$ $LastChangedBy$ * */@Servicepublic class XiaoMing {  public void printName() {  System.err.println("小明"); }}

我们都知道 @Autowired 可以根据类型( Type )进行自动注入,并且默认注入的bean为单例( SingleTon )的,那么我们可能会问,上面注入两次不会重复吗?答案是肯定的。而且每次注入的实例都是同一个实例。下面我们简单验证下:

@RestControllerpublic class MyController {  @Autowired private XiaoMing xiaoming;  @Autowired private XiaoMing wanger;  @RequestMapping(value = "/test.json", method = RequestMethod.GET) public String test() {  System.err.println(xiaoming);  System.err.println(wanger);  return "hello"; }}

调用上面的接口之后,将输出下面内容,可以看出两者为同一实例。

com.example.demo.beans.impl.XiaoMing@6afd4ce9
com.example.demo.beans.impl.XiaoMing@6afd4ce9

二、注入接口类型实例

如果我们要注入的类型声明为一个接口类型,而且该接口有1个以上的实现类,那么下面这段代码还能够正常运行吗?我们假设 Student 为接口, WangEr 和 XiaoMing 为两个实现类。

@Autowiredprivate Student stu1;@Autowiredprivate Student stu2;
@Servicepublic class XiaoMing implements Student {
@Servicepublic class WangEr implements Student {

答案是上面的代码不能正常运行,而且Spring 还启动报错了,原因是Spring想为 Student 注入一个单例的实例,但在注入的过程中意外地发现两个,所以报错,具体错误信息如下:

Field stu1 in com.example.demo.controller.MyController required a single bean, but 2 were found:
 - wangEr: defined in file [C:/Users/huangjiawei/Desktop/demo/target/classes/com/example/demo/beans/impl/WangEr.class]
 - xiaoMing: defined in file [C:/Users/huangjiawei/Desktop/demo/target/classes/com/example/demo/beans/impl/XiaoMing.class]

那该怎么弄才行呢?一般思路我们会想到为每个实现类分配一个id值,结果就有了下面的代码:

@Autowiredprivate Student stu1;@Autowiredprivate Student stu2;
@Service("stu1")public class XiaoMing implements Student {
@Service("stu2")public class WangEr implements Student {

做完上面的配置之后,Spring就会根据字段名称默认去bean工厂找相应的bean进行注入,注意名称不能够随便取的,要和注入的属性名一致。

三、总结

  1. 1、同一类型可以使用@Autowired注入多次,并且所有注入的实例都是同一个实例;
  2. 2、当对接口进行注入时,应该为每个实现类指明相应的id,则Spring将报错;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表