回顾
1.4.2 createBean(beanName, mbd, args)
我们讲获取 Bean 实例的过程
1.4.2.1 createBeanInstance(beanName, mbd, args)
通过构造函数创建 Bean 实例。
构造函数上如果有 @Autowired,会先将引用类型的入参对象优先实例化。
但此时的 Bean 实例里的属性上、非构造方法上如果有 @Autowired,还没有进行依赖注入。
1.4.2.2 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
请求 CommonAnnotationBeanPostProcessor 和 AutowiredAnnotationBeanPostProcessor,
扫描方法上是否有@PostConstruct @PreDestroy注解,有注解的封装成 LifecycleMetadata
扫描方法和属性上是否有@Resource注解
扫描方法和属性上是否有@Autowired @Value注解
对这些有注解的方法和属性封装成 InjectionMetadata
本节重点
本节的方法 populateBean 实现了对有 @Autowired 和 @Resource 的属性和非构造方法进行依赖注入。
无论是 CommonAnnotationBeanPostProcessor 还是 AutowiredAnnotationBeanPostProcessor,类的内部都有一个 map 来存储 InjectionMetadata
private final transient Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(256);
populateBean 这个方法正是从这个缓存里拿到的 InjectionMetadata,进而通过 InjectionMetadata 里的信息来进行依赖注入。当然,注入的实例会进行优先实例化。
跟源码
类 AbstractAutowireCapableBeanFactory
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;
//这里很有意思,写接口可以让所有类都不能依赖注入
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
//是否需要DI,依赖注入
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//不看
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null)

最低0.47元/天 解锁文章
2950

被折叠的 条评论
为什么被折叠?



