温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中@Autowired注入有什么用

发布时间:2021-08-05 09:38:34 来源:亿速云 阅读:130 作者:小新 栏目:编程语言

这篇文章主要介绍Spring中@Autowired注入有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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

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

@Autowired
private XiaoMing xiaoming;

@Autowired
private 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$
 *
 */
@Service
public class XiaoMing {
 
 public void printName() {
  System.err.println("小明");
 }
}

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

@RestController
public 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 为两个实现类。

@Autowired
private Student stu1;

@Autowired
private Student stu2;
@Service
public class XiaoMing implements Student {
@Service
public 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值,结果就有了下面的代码:

@Autowired
private Student stu1;

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

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

三、总结

  1. 同一类型可以使用@Autowired注入多次,并且所有注入的实例都是同一个实例;

  2. 当对接口进行注入时,应该为每个实现类指明相应的id,则Spring将报错;

以上是“Spring中@Autowired注入有什么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI