回顾:
在上一篇中, 我们提到 @EnableAspectJAutoProxy 注解给容器中加入了一个关键组件 internalAutoProxyCreator 的 BeanDefinition, 实际类型为
AnnotationAwareAspectJAutoProxyCreator 的 BeanDenation
并且发现这是一个后置处理器, 也是一个 XXXAware 接口的实现类. 以及探究了它的继承关系如下.
接下来我们就从后置处理器和 BeanFactoryAware 的角度来看看 AnnotationAwareAspectJAutoProxyCreator 的 BeanDefinition 创建完成后都做了什么.
一, 设置调试断点
我们分别进入四个有关类, 在类中与后置处理器和 BeanFactoryAware 有关的方法上打上断点. 最终效果如下:
AbstractAutoProxyCreator.setBeanFactory
AbstractAutoProxyCreator 有后置处理器逻辑
- {
- postProcessBeforeInstantiation()
- postProcessAfterInitialization()
- }
- AbstractAdvisorAutoProxyCreator.initBeanFactory
- AbstractAdvisorAutoProxyCreator.setBeanFactory
- AnnotationAwareAspectJAutoProxyCreator.initBeanFactory
最后, 在配置类中给两个 bean 方法打上断点.
二, 调试过程
开始调试, 我们会发现还是先来到上一篇的 AnnotationAwareAspectJAutoProxyCreator 的 BeanDenation 创建过程.
左下角 frames 框中选到 refresh 方法可以看到, AnnotationAwareAspectJAutoProxyCreator 的 BeanDenation 的创建是 invokeBeanFactoryPostProcessors() 方法调用来的.
调用这个方法在上下文中生成后置处理器的 BeanDefinition 加入容器中.
下一步的 registerBeanPostProcessors 才是注册后置处理器 (利用 BeanDefinition 的信息注册对应 Bean), 也是本篇的重点.
为了让它快速创建完 BeanDefinition, 这里我们直接快进到下一个断点.
程序先来到了 AbstractAdvisorAutoProxyCreator 的 setBeanFactory 方法
为了从头看起, 还是先在 frames 框中选到 refresh 方法, 可以看到来到了 refresh 的下一方法, 将要开始注册后置处理器.
二点一, registerBeanPostProcessors()
我们继续在 frames 中往上点, 直到来到 PostProcessorRegistrationDelegate.registerBeanPostProcessors()
方法有点长, 但关键只在其中几个地方, 我们将在下面进行针对分析
- public static void registerBeanPostProcessors(
- ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
- String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
- // Register BeanPostProcessorChecker that logs an info message when
- // a bean is created during BeanPostProcessor instantiation, i.e. when
- // a bean is not eligible for getting processed by all BeanPostProcessors.
- int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
- beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
- // Separate between BeanPostProcessors that implement PriorityOrdered,
- // Ordered, and the REST.
- List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
- List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
- List<String> orderedPostProcessorNames = new ArrayList<String>();
- List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
- for (String ppName : postProcessorNames) {
- if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
- priorityOrderedPostProcessors.add(pp);
- if (pp instanceof MergedBeanDefinitionPostProcessor) {
- internalPostProcessors.add(pp);
- }
- }
- else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
- orderedPostProcessorNames.add(ppName);
- }
- else {
- nonOrderedPostProcessorNames.add(ppName);
- }
- }
- // First, register the BeanPostProcessors that implement PriorityOrdered.
- sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
- registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
- // Next, register the BeanPostProcessors that implement Ordered.
- List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
- for (String ppName : orderedPostProcessorNames) {
- BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
- orderedPostProcessors.add(pp);
- if (pp instanceof MergedBeanDefinitionPostProcessor) {
- internalPostProcessors.add(pp);
- }
- }
- sortPostProcessors(orderedPostProcessors, beanFactory);
- registerBeanPostProcessors(beanFactory, orderedPostProcessors);
- // Now, register all regular BeanPostProcessors.
- List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
- for (String ppName : nonOrderedPostProcessorNames) {
- BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
- nonOrderedPostProcessors.add(pp);
- if (pp instanceof MergedBeanDefinitionPostProcessor) {
- internalPostProcessors.add(pp);
- }
- }
- registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
- // Finally, re-register all internal BeanPostProcessors.
- sortPostProcessors(internalPostProcessors, beanFactory);
- registerBeanPostProcessors(beanFactory, internalPostProcessors);
- // Re-register post-processor for detecting inner beans as ApplicationListeners,
- // moving it to the end of the processor chain (for picking up proxies etc).
- beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
- }
- registerBeanPostProcessors
4: 获取所有后置处理器的名字
14~32: 对实现不同接口的后置处理器进行分类
35~48: 对上面的分类分别进行处理, 因为实现的是 Ordered 接口, 我们只关注 39~48 行
40~46: 遍历分好的实现了 Ordered 接口的后置处理器名, 利用 beanFactory.getBean(ppName, BeanPostProcessor.class) 来获取
二点二, doGetBean()
有了以上的步骤, 我们主要来看 beanFactory 是怎么获取的
可以看到, 先来到了 getBean 方法, 然后又进入了 doGetBean 方法. 下面我们来看 doGetBean 做了什么.
- /**
- * Return an instance, which may be shared or independent, of the specified bean.
- * @param name the name of the bean to retrieve
- * @param requiredType the required type of the bean to retrieve
- * @param args arguments to use when creating a bean instance using explicit arguments
- * (only applied when creating a new instance as opposed to retrieving an existing one)
- * @param typeCheckOnly whether the instance is obtained for a type check,
- * not for actual use
- * @return an instance of the bean
- * @throws BeansException if the bean could not be created
- */
- @SuppressWarnings("unchecked")
- protected <T> T doGetBean(
- final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
- throws BeansException {
- final String beanName = transformedBeanName(name);
- Object bean;
- // Eagerly check singleton cache for manually registered singletons.
- Object sharedInstance = getSingleton(beanName);
- if (sharedInstance != null && args == null) {
- if (logger.isDebugEnabled()) {
- if (isSingletonCurrentlyInCreation(beanName)) {
- logger.debug("Returning eagerly cached instance of singleton bean'" + beanName +
- "'that is not fully initialized yet - a consequence of a circular reference");
- }
- else {
- logger.debug("Returning cached instance of singleton bean'" + beanName + "'");
- }
- }
- bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
- }
- else {
- // Fail if we're already creating this bean instance:
- // We're assumably within a circular reference.
- if (isPrototypeCurrentlyInCreation(beanName)) {
- throw new BeanCurrentlyInCreationException(beanName);
- }
- // Check if bean definition exists in this factory.
- BeanFactory parentBeanFactory = getParentBeanFactory();
- if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
- // Not found -> check parent.
- String nameToLookup = originalBeanName(name);
- if (args != null) {
- // Delegation to parent with explicit args.
- return (T) parentBeanFactory.getBean(nameToLookup, args);
- }
- else {
- // No args -> delegate to standard getBean method.
- return parentBeanFactory.getBean(nameToLookup, requiredType);
- }
- }
- if (!typeCheckOnly) {
- markBeanAsCreated(beanName);
- }
- try {
- final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
- checkMergedBeanDefinition(mbd, beanName, args);
- // Guarantee initialization of beans that the current bean depends on.
- String[] dependsOn = mbd.getDependsOn();
- if (dependsOn != null) {
- for (String dep : dependsOn) {
- if (isDependent(beanName, dep)) {
- throw new BeanCreationException(mbd.getResourceDescription(), beanName,
- "Circular depends-on relationship between'" + beanName + "'and'" + dep + "'");
- }
- registerDependentBean(dep, beanName);
- getBean(dep);
- }
- }
- // Create bean instance.
- if (mbd.isSingleton()) {
- sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
- @Override
- public Object getObject() throws BeansException {
- try {
- return createBean(beanName, mbd, args);
- }
- catch (BeansException ex) {
- // Explicitly remove instance from singleton cache: It might have been put there
- // eagerly by the creation process, to allow for circular reference resolution.
- // Also remove any beans that received a temporary reference to the bean.
- destroySingleton(beanName);
- throw ex;
- }
- }
- });
- bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
- }
- else if (mbd.isPrototype()) {
- // It's a prototype -> create a new instance.
- Object prototypeInstance = null;
- try {
- beforePrototypeCreation(beanName);
- prototypeInstance = createBean(beanName, mbd, args);
- }
- finally {
- afterPrototypeCreation(beanName);
- }
- bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
- }
- else {
- String scopeName = mbd.getScope();
- final Scope scope = this.scopes.get(scopeName);
- if (scope == null) {
- throw new IllegalStateException("No Scope registered for scope name'" + scopeName + "'");
- }
- try {
- Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
- @Override
- public Object getObject() throws BeansException {
- beforePrototypeCreation(beanName);
- try {
- return createBean(beanName, mbd, args);
- }
- finally {
- afterPrototypeCreation(beanName);
- }
- }
- });
- bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
- }
- catch (IllegalStateException ex) {
- throw new BeanCreationException(beanName,
- "Scope'" + scopeName + "'is not active for the current thread; consider" +
- "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
- ex);
- }
- }
- }
- catch (BeansException ex) {
- cleanupAfterBeanCreationFailure(beanName);
- throw ex;
- }
- }
- // Check if required type matches the type of the actual bean instance.
- if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
- try {
- return getTypeConverter().convertIfNecessary(bean, requiredType);
- }
- catch (TypeMismatchException ex) {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed to convert bean'" + name + "'to required type'" +
- ClassUtils.getQualifiedName(requiredType) + "'", ex);
- }
- throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
- }
- }
- return (T) bean;
- }
- AbstractBeanFactory.doGetBean
17: 获取后置处理器的名称 (这里也就是 internalAutoProxyCreator)
21: 根据 bean 名字获取对应单例
22~33: 如果获取到的 bean 不为空, 进行一系列操作 (这里的 internalAutoProxyCreator 是第一次获取, bean 应该是空, 所以我们跳过 22~33)
61:getMergedLocalBeanDefinition() 根据传入的后置处理器名称, 获取其所有信息, 在这里也就是从 internalAutoProxyCreator 的 BeanDefinition 中获取必要信息, 这是为创建 bean 做准备.
79: 判断如果是单例, 调用 getSingleton() 来获取
这里我们先不急着进入 getSingleton() 方法, 接着往下看先.
130:bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd) 将 79 行获取的 scopedInstance 包装为 bean
159: 返回 bean
ok,getSingleton() 的获取是要返回的, 所以这步是关键, 接下来我们来看看 getSingleton().
一直往上走, 最终我们来到 doCreateBean(), 说明获取不到, 接下来需要创建 bean 了
二点三, doCreateBean()
- /**
- * Actually create the specified bean. Pre-creation processing has already happened
- * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
- * <p>Differentiates between default bean instantiation, use of a
- * factory method, and autowiring a constructor.
- * @param beanName the name of the bean
- * @param mbd the merged bean definition for the bean
- * @param args explicit arguments to use for constructor or factory method invocation
- * @return a new instance of the bean
- * @throws BeanCreationException if the bean could not be created
- * @see #instantiateBean
- * @see #instantiateUsingFactoryMethod
- * @see #autowireConstructor
- */
- protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
- throws BeanCreationException {
- // Instantiate the bean.
- BeanWrapper instanceWrapper = null;
- if (mbd.isSingleton()) {
- instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
- }
- if (instanceWrapper == null) {
- instanceWrapper = createBeanInstance(beanName, mbd, args);
- }
- final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
- Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
- mbd.resolvedTargetType = beanType;
- // Allow post-processors to modify the merged bean definition.
- synchronized (mbd.postProcessingLock) {
- if (!mbd.postProcessed) {
- try {
- applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
- }
- catch (Throwable ex) {
- throw new BeanCreationException(mbd.getResourceDescription(), beanName,
- "Post-processing of merged bean definition failed", ex);
- }
- mbd.postProcessed = true;
- }
- }
- // Eagerly cache singletons to be able to resolve circular references
- // even when triggered by lifecycle interfaces like BeanFactoryAware.
- boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
- isSingletonCurrentlyInCreation(beanName));
- if (earlySingletonExposure) {
- if (logger.isDebugEnabled()) {
- logger.debug("Eagerly caching bean'" + beanName +
- "'to allow for resolving potential circular references");
- }
- addSingletonFactory(beanName, new ObjectFactory<Object>() {
- @Override
- public Object getObject() throws BeansException {
- return getEarlyBeanReference(beanName, mbd, bean);
- }
- });
- }
- // Initialize the bean instance.
- Object exposedObject = bean;
- try {
- populateBean(beanName, mbd, instanceWrapper);
- if (exposedObject != null) {
- exposedObject = initializeBean(beanName, exposedObject, mbd);
- }
- }
- catch (Throwable ex) {
- if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
- throw (BeanCreationException) ex;
- }
- else {
- throw new BeanCreationException(
- mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
- }
- }
- if (earlySingletonExposure) {
- Object earlySingletonReference = getSingleton(beanName, false);
- if (earlySingletonReference != null) {
- if (exposedObject == bean) {
- exposedObject = earlySingletonReference;
- }
- else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
- String[] dependentBeans = getDependentBeans(beanName);
- Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
- for (String dependentBean : dependentBeans) {
- if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
- actualDependentBeans.add(dependentBean);
- }
- }
- if (!actualDependentBeans.isEmpty()) {
- throw new BeanCurrentlyInCreationException(beanName,
- "Bean with name'" + beanName + "'has been injected into other beans [" +
- StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
- "] in its raw version as part of a circular reference, but has eventually been" +
- "wrapped. This means that said other beans do not use the final version of the" +
- "bean. This is often the result of over-eager type matching - consider using" +
- "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
- }
- }
- }
- }
- // Register bean as disposable.
- try {
- registerDisposableBeanIfNecessary(beanName, bean, mbd);
- }
- catch (BeanDefinitionValidationException ex) {
- throw new BeanCreationException(
- mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
- }
- return exposedObject;
- }
- AbstractAutowireCapableBeanFactory.doCreateBean
26: 创建 bean
64:populateBean(beanName, mbd, instanceWrapper) 给 bean 的属性赋值
66:initializeBean(beanName, exposedObject, mbd) 初始化 bean
下面我们来看这个初始化 bean 都做了什么
二点四, initializeBean()
- /**
- * Initialize the given bean instance, applying factory callbacks
- * as well as init methods and bean post processors.
- * <p>Called from {@link #createBean} for traditionally defined beans,
- * and from {@link #initializeBean} for existing bean instances.
- * @param beanName the bean name in the factory (for debugging purposes)
- * @param bean the new bean instance we may need to initialize
- * @param mbd the bean definition that the bean was created with
- * (can also be {@code null}, if given an existing bean instance)
- * @return the initialized bean instance (potentially wrapped)
- * @see BeanNameAware
- * @see BeanClassLoaderAware
- * @see BeanFactoryAware
- * @see #applyBeanPostProcessorsBeforeInitialization
- * @see #invokeInitMethods
- * @see #applyBeanPostProcessorsAfterInitialization
- */
- protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
- if (System.getSecurityManager() != null) {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- @Override
- public Object run() {
- invokeAwareMethods(beanName, bean);
- return null;
- }
- }, getAccessControlContext());
- }
- else {
- invokeAwareMethods(beanName, bean);
- }
- Object wrappedBean = bean;
- if (mbd == null || !mbd.isSynthetic()) {
- wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
- }
- try {
- invokeInitMethods(beanName, wrappedBean, mbd);
- }
- catch (Throwable ex) {
- throw new BeanCreationException(
- (mbd != null ? mbd.getResourceDescription() : null),
- beanName, "Invocation of init method failed", ex);
- }
- if (mbd == null || !mbd.isSynthetic()) {
- wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
- }
- return wrappedBean;
- }
- AbstractAutowireCapableBeanFactory.initializeBean
一进来我们是停在 29 行的 invokeAwareMethods(beanName, bean), 这里先不看它
我们来关注一下 initializeBean 的几个重要流程
1,invokeAwareMethods
2,34 行 applyBeanPostProcessorsBeforeInitialization
3,38 行 invokeInitMethods
4,47 行 applyBeanPostProcessorsAfterInitialization
先执行 invokeAwareMethods, 调用那些 XXXAware 方法, 然后执行后置处理器的 applyBeanPostProcessorsBeforeInitialization 方法, 接着执行初始化方法, 最后执行后置处理器的 applyBeanPostProcessorsAfterInitialization 方法, 这也是我们的后置处理器为什么能在 bean 初始化前后调用方法的原因了.
现在我们往下进入 invokeAwareMethods
- private void invokeAwareMethods(final String beanName, final Object bean) {
- if (bean instanceof Aware) {
- if (bean instanceof BeanNameAware) {
- ((BeanNameAware) bean).setBeanName(beanName);
- }
- if (bean instanceof BeanClassLoaderAware) {
- ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
- }
- if (bean instanceof BeanFactoryAware) {
- ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
- }
- }
- }
- invokeAwareMethods
invokeAwareMethods 方法先判断是哪个类型的 Aware 接口, 然后调用对应的 set 方法, 所以它最终来到了我们的断点, setBeanFactory() 方法
接下来我们一路点击下一步, 直到下图, 这个 BeanPostProcessor 就创建完了, 并通过 orderedPostProcessors.add(pp) 先添加到 orderedPostProcessors 中
再通过 registerBeanPostProcessors(beanFactory, orderedPostProcessors) 添加到 beanFactory 中
总结
以上整个过程, 是创建完 AnnotationAwareAspectJAutoProxyCreator 后置处理器 bean 并存入 beanFactory 的过程.
下一篇将来探寻 AnnotationAwareAspectJAutoProxyCreator 在作为后置处理器存入 bean 工程之后的事.
今天是悲伤, 再见了爱人,
来源: https://www.cnblogs.com/Unicron/p/12403620.html