服务器之家

服务器之家 > 正文

Spring中@Autowire注入的深入讲解

时间:2020-09-21 00:26     来源/作者:Real dream

一直在思考spring的@Autowire注入属性时到底是按类型注入还是按名称注入,今天写了一个测试来证明一下。

定义接口TestService

?
1
2
3
public interface TestService {
 void test();
}

定义接口实现:TestServiceImpl1和TestServiceImpl2

?
1
2
3
4
5
6
7
@Service
public class TestServiceImpl1 implements TestService {
 
 public void test() {
  System.out.println(1111);
 }
}
?
1
2
3
4
5
6
7
@Service
public class TestServiceImpl2 implements TestService {
 
 public void test() {
  System.out.println(2222);
 }
}

定义一个bean依赖TestService,

?
1
2
3
4
5
6
7
8
9
10
@Controller
public class TestController {
    //此时的beanBame=testService
 @Autowired
 TestService testService;
 
 public void test(){
  testService.test();
 }
}

编写测试类:

?
1
2
3
4
5
6
7
8
9
10
11
@Configuration
@ComponentScan("test")
public class Test {
 public static void main(String[] args) {
  AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
  context.register(Test.class);
  context.refresh();
  TestService bean = context.getBean(TestService.class);
  bean.test();
 }
}

启动项目跟踪源码:在spring工厂初始化Bean填充属性的时候,AbstractAutowireCapableBeanFactory.populateBean()方法中会执行后置处理器AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues() ,继续跟踪,在DefaultListableBeanFactory.doResolveDependency()方法中的findAutowireCandidates()根据类型匹配到两个Bean,见截图:

Spring中@Autowire注入的深入讲解

由于获取的Bean超过两个,spring会根据名称去匹配,如果匹配成功则返回对应的bean;如果匹配失败,则会抛出异常。如图:

Spring中@Autowire注入的深入讲解

到此为止,我们已经能发现@Autowire注解注入属性的原理:先根据类型注入,如果获取到多个Bean,则根据名称匹配,若名称未匹配上就抛出异常。

总结

到此这篇关于Spring中@Autowire注入的文章就介绍到这了,更多相关Spring中@Autowire注入内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_39600860/article/details/108678305

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部