相关文章
Spring IOC系列学习笔记一:前置刷新
Spring IOC系列学习笔记二:obtainFreshBeanFactory方法
Spring IOC系列学习笔记三:parseDefaultElement详解
Spring IOC系列学习笔记四:parseCustomElement解析
Spring IOC系列学习笔记五:context:component-scan 节点解析
Spring IOC系列学习笔记六:invokeBeanFactoryPostProcessors解析
Spring IOC系列学习笔记七:registerBeanPostProcessors
Spring IOC系列学习笔记八:finishBeanFactoryInitialization
Spring IOC系列学习笔记九:getBean方法
Spring IOC系列学习笔记十:createBean方法(上)
Spring IOC系列学习笔记十一:createBean方法(下)
Spring IOC系列学习笔记十二:@Autowire注解
文章目录
- 相关文章
- 前言
- 开启Spring的注解配置
- 代码中使用
- 继承结构
- 源码解析
- 构造函数注入
- 属性注入
- postProcessMergedBeanDefinition方法介绍
- AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition
- 代码块二:findAutowiringMetadata
- 代码块三:buildAutowiringMetadata
- 代码块四:checkConfigMembers
- AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues
- 代码块五:inject
- 代码块六:AutowiredAnnotationBeanPostProcessor#inject
- 代码块七:registerDependentBeans
- 总结
前言
我们介绍一个我们在Spring开发中的最常用的注解@Autowire,在前面createBean方法(上)的代码块三的4.2和createBean方法(下)的代码块一和代码块四的8.2进行简单介绍,这是两个解析@Autowire的入口。
开启Spring的注解配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="zgf"></context:component-scan>
</beans>
代码中使用
@Component(value = "accountService")
public class AccountServiceImpl implements IAccountService {
1、属性注入
@Autowired
private IAccountDao accountDao ;
2、构造函数注入
@Autowired
public AccountServiceImpl(IAccountDao accountDao) {
this.accountDao = accountDao;
}
}
其实Spring更倾向于我们使用构造函数注入,
继承结构
源码解析
AutowiredAnnotationBeanPostProcessor 何时被注册到 BeanFactory?
在context:component-scan 节点详解的代码块十五注入了一系列的注解解析就包括了AutowiredAnnotationBeanPostProcessor,原代码如下:
AnnotationConfigUtils#registerAnnotationConfigProcessors
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
// 1.设置dependencyComparator属性
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
// 2.设置autowireCandidateResolver属性(设置自动注入候选对象的解析器,用于判断BeanDefinition是否为候选对象)
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4);
// 3.注册内部管理的用于处理@Configuration注解的后置处理器的bean
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
// 3.1 registerPostProcessor: 注册BeanDefinition到注册表中
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 4.注册内部管理的用于处理@Autowired、@Value、@Inject以及@Lookup注解的后置处理器的bean
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 5.注册内部管理的用于处理@Required注解的后置处理器的bean
if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 6.注册内部管理的用于处理JSR-250注解(例如@Resource, @PostConstruct, @PreDestroy)的后置处理器的bean
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 7.注册内部管理的用于处理JPA注解的后置处理器的bean
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 8.注册内部管理的用于处理@EventListener注解的后置处理器的bean
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
// 9.注册内部管理用于生产ApplicationListener对象的EventListenerFactory对象
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
构造函数注入
构造函数注入通常来说有两种:1)xml 配置注入;2)@Autowire 注解注入;本文只讨论 @Autowire 注解注入。
AutowiredAnnotationBeanPostProcessor 中重写的方法不多,直接找一下就可以找到跟构造函数相关的方法:determineCandidateConstructors,该方法被定义在 SmartInstantiationAwareBeanPostProcessor 接口中,主要作用是:确定要用于给定 bean 的候选构造函数。
determineCandidateConstructors方法的入口在createBean(上)的代码块五
AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
// Let's check for lookup methods here..
1、@Lookup注解检查
if (!this.lookupMethodsChecked.contains(beanName)) {
try {
ReflectionUtils.doWithMethods(beanClass, method -> {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
Assert.state(beanFactory != null, "No BeanFactory available");
LookupOverride override = new LookupOverride(method, lookup.value());
try {
RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
}
});
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
}
1.1、放到缓存中
this.lookupMethodsChecked.add(beanName);
}
// Quick check on the concurrent map first, with minimal locking.
2、构造函数解析,先从换缓存中获取已经解析的构造函数
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
// Fully synchronized resolution now...
synchronized (this.candidateConstructorsCache) {
candidateConstructors = this.candidateConstructorsCache.get(beanClass);
2.1、双重检查
if (candidateConstructors == null) {
Constructor<?>[] rawCandidates;
try {
2.2、获取该类的所有的构造函数
rawCandidates = beanClass.getDeclaredConstructors();
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
2.4、用于存放使用了@Autowired的构造函数
List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length);
2.5、@Autowired的required为true的构造函数
Constructor<?> requiredConstructor = null;
2.6、默认的构造函数
Constructor<?> defaultConstructor = null;
2.7、这个是干啥的不知道
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
2.8、不是复杂的构造函数的个数
int nonSyntheticConstructors = 0;
for (Constructor<?> candidate : rawCandidates) {
if (!candidate.isSynthetic()) {
2.9、不是复杂的构造函数就++
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
continue;
}
2.10、查看这个构造函数是否使用了@Autowired注解
AnnotationAttributes ann = findAutowiredAnnotation(candidate);
if (ann == null) {
2.11、如果没有从候选者找到注解,则尝试解析beanClass的原始类
Class<?> userClass = ClassUtils.getUserClass(beanClass);
if (userClass != beanClass) {
try {
Constructor<?> superCtor =
userClass.getDeclaredConstructor(candidate.getParameterTypes());
ann = findAutowiredAnnotation(superCtor);
}
catch (NoSuchMethodException ex) {
// Simply proceed, no equivalent superclass constructor found...
}
}
}
if (ann != null) {
2.12、@Autowired的构造函数只能有一个required为true
2.13、requiredConstructor不为空说明已经缓存了一个为true的构造函数,现在又找到一个所以需要抛出异常
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
2.14、确定required的属性true或false
boolean required = determineRequiredStatus(ann);
if (required) {
2.15、这儿和2.13是相同的作用
if (!candidates.isEmpty()) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructors: " + candidates +
". Found constructor with 'required' Autowired annotation: " +
candidate);
}
2.16、required为true的构造函数
requiredConstructor = candidate;
}
2.17、把使用了@Autowired的构造函数加入到candidates缓存
candidates.add(candidate);
}
else if (candidate.getParameterCount() == 0) {
2.18、如果当前构造函数没有参数,则是默认的构造函数
defaultConstructor = candidate;
}
}
3、到这儿循环结束,查看有几个构造函数使用了@Autowired注解
if (!candidates.isEmpty()) {
// Add default constructor to list of optional constructors, as fallback.
if (requiredConstructor == null) {
if (defaultConstructor != null) {
3.1、没有@Autowired且required为true的构造函数,但是有默认的构造函数,则加入缓存
candidates.add(defaultConstructor);
}
else if (candidates.size() == 1 && logger.isWarnEnabled()) {
logger.warn("Inconsistent constructor declaration on bean with name '" + beanName +
"': single autowire-marked constructor flagged as optional - " +
"this constructor is effectively required since there is no " +
"default constructor to fall back to: " + candidates.get(0));
}
}
candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
}
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
else if (nonSyntheticConstructors == 2 && primaryConstructor != null && defaultConstructor != null) {
candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
}
else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
candidateConstructors = new Constructor<?>[] {primaryConstructor};
}
else {
candidateConstructors = new Constructor<?>[0];
}
4、将构造函数放入到缓存中
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
2.10、查看这个构造函数是否使用了@Autowired注解见代码块一
代码块一:findAutowiredAnnotation
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
// 1.判断ao是否有被注解修饰
if (ao.getAnnotations().length > 0) {
// 2.检查是否有autowiredAnnotationTypes中的注解:@Autowired、@Value(@Value无法修饰构造函数)
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
// 3.拿到注解的合并注解属性,@Autowire在这边拿到,required=true(默认属性)
AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
if (attributes != null) {
return attributes;
}
}
}
return null;
}
属性注入
属性注入通常来说有两种:1)xml 配置注入;2)@Autowire 注解注入;本文只讨论 @Autowire 注解注入。
AutowiredAnnotationBeanPostProcessor 中跟属性注入有关的方法出口有两个:postProcessMergedBeanDefinition 和 postProcessPropertyValues。
postProcessMergedBeanDefinition 入口在createBean(下)的代码块一
postProcessPropertyValues入口在cereteBean(下)的代码块四8.2
postProcessMergedBeanDefinition方法介绍
AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (beanType != null) {
1.在指定Bean中查找使用@Autowire注解的元数据
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
2.检查元数据中的注解信息
metadata.checkConfigMembers(beanDefinition);
}
}
1.在指定 bean 中查找使用 @Autowire 注解的元数据,见代码块二详解。
2.检查元数据中的注解信息,见代码块四详解。
代码块二:findAutowiringMetadata
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// Fall back to class name as cache key, for backwards compatibility with custom callers.
1、cacheKey是beanName或者class的Name
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// Quick check on the concurrent map first, with minimal locking.
2、spring的一致套路先从缓存中获取,没有的话解析然后放入到缓存中
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
2.1、双重检查
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
2.2、先清除
if (metadata != null) {
metadata.clear(pvs);
}
2.3、解析@Autowired注解的信息,生成元数据(包含clazz和clazz里解析到的注入的元素
2.4、这里的元素包括AutowiredFieldElement和AutowiredMethodElement)
metadata = buildAutowiringMetadata(clazz);
2.5、将解析的元数据放到injectionMetadataCache缓存
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
2.3、解析@Autowired注解的信息,生成元数据(包含clazz和clazz里解析到的注入的元素见代码块三
代码块三:buildAutowiringMetadata
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
1、用于存放所有解析到的注入的元素的变量
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
Class<?> targetClass = clazz;
do {
2、定义存放当前类解析的元素(有序存放链表)
final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
ReflectionUtils.doWithLocalFields(targetClass, field -> {
2.1、找到用@Autowired注解的字段
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
2.2、@Autowired不支持静态类型的字段
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
return;
}
2.3、获取required的属性
boolean required = determineRequiredStatus(ann);
2.4、把field和required封装成AutowiredFieldElement放入到缓存中
currElements.add(new AutowiredFieldElement(field, required));
}
});
3、如果targetClass的方法上有@Autowired注解,则用工具类获取注解信息
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
3、1、找到桥接方法
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
3.2、判断方法可见性,不可见直接返回
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
3.3、方法是否使用了@Autowired注解
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
3.4、判断方法是不是静态的
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
3.5、判断方法是否有参数,spring注入就是要注入参数的,没有参数的话没有意义
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
3.6、获取required的属性
boolean required = determineRequiredStatus(ann);
3.7、获取method的属性描述器
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
3.8、把method, required, pd封装成AutowiredMethodElement放入到缓存
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
4、本次循环获取到的注解信息放入到缓存中
elements.addAll(0, currElements);
5、递归的解析父类
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
6、封装成InjectionMetadata返回
return new InjectionMetadata(clazz, elements);
}
代码块四:checkConfigMembers
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<InjectedElement> checkedElements = new LinkedHashSet<InjectedElement>(this.injectedElements.size());
1.遍历检查所有要注入的元素
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
2.如果beanDefinition的externallyManagedConfigMembers属性不包含该member
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
3.将该member添加到beanDefinition的externallyManagedConfigMembers属性
beanDefinition.registerExternallyManagedConfigMember(member);
4.并将element添加到checkedElements
checkedElements.add(element);
if (logger.isDebugEnabled()) {
logger.debug("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
5.赋值给checkedElements(检查过的元素)
this.checkedElements = checkedElements;
}
AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
1、找到@Autowired注解的元数据
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
2、执行属性注入或者方法注入
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
1、找到@Autowired注解的元数据见代码块二
2、执行注入见代码块五
代码块五:inject
public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
1.如果checkedElements存在,则使用checkedElements,否则使用injectedElements
Collection<InjectedElement> elementsToIterate =
(this.checkedElements != null ? this.checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
boolean debug = logger.isDebugEnabled();
for (InjectedElement element : elementsToIterate) {
if (debug) {
logger.debug("Processing injected element of bean '" + beanName + "': " + element);
}
2.解析@Autowired注解生成的元数据类:AutowiredFieldElement、AutowiredMethodElement,
这两个类继承InjectionMetadata.InjectedElement,各自重写了inject方法。
element.inject(target, beanName, pvs);
}
}
}
2.解析@Autowired注解生成的元数据类见代码块六
代码块六:AutowiredAnnotationBeanPostProcessor#inject
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
1、拿到该属性
Field field = (Field) this.member;
Object value;
2、先从缓存中解析属性
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
3、解析属性获取该属性的bean实例,把beanName封装到autowiredBeanNames中
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
4、value不为空或者required为true
if (value != null || this.required) {
4.1、如果属性依赖注入的bean不止一个(Array,Collection,Map),缓存cachedFieldValue放的是DependencyDescriptor
this.cachedFieldValue = desc;
4.2、注册依赖关系
registerDependentBeans(beanName, autowiredBeanNames);
4.3、autowiredBeanNames唯一
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName)) {
4.4、检查autowiredBeanName对应的bean的类型是否为field的类型
4.5、@Autowired标识属性类型和Bean的类型要匹配,因此Array,Collection,Map类型的属性不支持缓存属性Bean名称
if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
}
else {
this.cachedFieldValue = null;
}
5、缓存标识
this.cached = true;
}
}
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
6、通过反射为属性赋值
field.set(bean, value);
}
}
}
3、解析属性获取该属性的bean实例在createBean(上)的代码块十
4.2、注册依赖关系见代码块七
代码块七:registerDependentBeans
private void registerDependentBeans(String beanName, Set<String> autowiredBeanNames) {
if (beanName != null) {
1.遍历所有autowiredBeanNames
for (String autowiredBeanName : autowiredBeanNames) {
if (this.beanFactory.containsBean(autowiredBeanName)) {
2.如果autowiredBeanName在BeanFactory中存在,则注册依赖关系到缓存(beanName 依赖 autowiredBeanName)
this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' to bean named '" + autowiredBeanName + "'");
}
}
}
}
2、注册依赖关系在getBean的代码块八
总结
本文简单的介绍了 @Autowire 常见的用法,并对 Spring IoC 构建过程 @Autowire 注解相关的方法进行了解析。