重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Spring中@Autowired注入有什么用

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

创新互联专注于企业成都全网营销、网站重做改版、柴桑网站定制设计、自适应品牌网站建设、H5响应式网站成都做商城网站、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为柴桑等各大城市提供网站开发制作服务。

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

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

@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注入有什么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


本文题目:Spring中@Autowired注入有什么用
转载源于:http://cqcxhl.cn/article/jceedg.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP