@Autwired
一、作用:
注入业务需要的对象
二、实现原理
- 1、猜测:
打开源码可知
只有几个简单的元注解。而对于注解,首先要在bean初始化时扫描并标注,在bean填充阶段,将所需注入的对象封装注入bean中。同理猜测- 通过反射查找bean的class下标注了@Autowired的字段
- 获取对应的bean,再通过反射调用将bean注入
- 2、源码
- AutowiredAnnotationBeanPostProcessor为@Autowired的实现类,看bean的注册部分
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
//【第一步】Bean的加载和注册
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
//【第二步】注册Bean后置处理器,注册到DefaultListableBeanFactory(它的父类)中的一个List存放后置处理器
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
//【第三步】实例化单利且lazy-init=false的Bean
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
第一步,加载解析注册bean,第二步,注册后置处理器,第三部,实例化bean并注入属性