温馨提示×

温馨提示×

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

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

一文带你了解Spring中的@Autowire注入

发布时间:2020-11-02 17:14:36 来源:亿速云 阅读:207 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关一文带你了解Spring中的@Autowire注入,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

定义接口TestService

public interface TestService {
 void test();
}

定义接口实现:TestServiceImpl1和TestServiceImpl2

@Service
public class TestServiceImpl1 implements TestService {

 public void test() {
  System.out.println(1111);
 }
}
@Service
public class TestServiceImpl2 implements TestService {

 public void test() {
  System.out.println(2222);
 }
}

定义一个bean依赖TestService,

@Controller
public class TestController {
	//此时的beanBame=testService
 @Autowired
 TestService testService;

 public void test(){
  testService.test();
 }
}

编写测试类:

@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注入了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

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

AI