关于springboot:Spring-Boot-如何处理Resource

51次阅读

共计 2259 个字符,预计需要花费 6 分钟才能阅读完成。

先造一个测试用例:

public class TransactionServiceTest {
    @Resource
    private IQrcodeAdScheduleService qrcodeAdScheduleService;
}

而后启动 Spring Boot 能够看到上面的调用栈信息:
图 1

由上图可知,在创立完 bean 实例后,通过 applyMergedBeanDefinitionPostProcessors() 批改 beanDefinition 构造 ( 针对这种场景能够了解为解析 @Resource 对应的 bean 信息)

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof MergedBeanDefinitionPostProcessor) {MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                // 执行 CommonAnnotationBeanPostProcessor 类 postProcessMergedBeanDefinition()
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }

图 2
有图 2 可知,解决 @Resource 的 PostProcessor 是“CommonAnnotationBeanPostProcessor”,而后看一下 CommonAnnotationBeanPostProcessor 的局部细节:

private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
        Class<?> targetClass = clazz;

        do {
            final LinkedList<InjectionMetadata.InjectedElement> currElements =
                    new LinkedList<>();

            ReflectionUtils.doWithLocalFields(targetClass, field -> {if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {if (Modifier.isStatic(field.getModifiers())) {throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields");
                    }
                    currElements.add(new WebServiceRefElement(field, field, null));
                }
                else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) {if (Modifier.isStatic(field.getModifiers())) {throw new IllegalStateException("@EJB annotation is not supported on static fields");
                    }
                    currElements.add(new EjbRefElement(field, field, null));
                }
                // 解析 @Resource.class
                else if (field.isAnnotationPresent(Resource.class)) {if (Modifier.isStatic(field.getModifiers())) {throw new IllegalStateException("@Resource annotation is not supported on static fields");
                    }
                    if (!ignoredResourceTypes.contains(field.getType().getName())) {currElements.add(new ResourceElement(field, field, null));
                    }
                }
            });
}

下面的代码块呈现了期待已久的“Resource.class”关键字,咱们就释怀了。咱们再回顾一下,
其流程是这样的:在 AbstractAutowireCapableBeanFactory.populateBean()->ibp.postProcessPropertyValue()->CommonAnnotationBeanPostProcessor.postProcessPropertyValue() 去实例化 @Resource 作用的 bean;

除了和解决 @Autowired 不是一个 PostProcessor(解决 @AutoWireds 是用这个“AutowiredAnnotationBeanPostProcessor”PostProcessor)其余解决流程和 @Autowired 的解决流程一毛一样啊!

正文完
 0