zoukankan      html  css  js  c++  java
  • springAOP源码分析之篇二:代理对象的生成

    在xml解析好以后再在代理对象生成的过程中将生成6个对象
    userDao:目标对象
    logger:定义的切面
    InternalAutoProxyCreator:用来生成代理对象的后置处理器,它实现了BeanPostProcessor,类型是AspectJAwareAdvisorAutoProxyCreator
    AspectJPointcutAdvisor#0:定义的通知
    AspectJPointcutAdvisor#1:定义的通知
    updateUserMethod:切入点表达式
    AspectJAwareAdvisorAutoProxyCreator 实现了BeanPostProcessor接口,他在Bean实例化注册BeanPostProcessor的
    过程中生成AspectJAwareAdvisorAutoProxyCreator代理对象

    synchronized (this.startupShutdownMonitor) {
                // Prepare this context for refreshing.
                prepareRefresh();
    
                // Tell the subclass to refresh the internal bean factory.
                ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
                // Prepare the bean factory for use in this context.
                prepareBeanFactory(beanFactory);
    
                try {
                    // Allows post-processing of the bean factory in context subclasses.
                    postProcessBeanFactory(beanFactory);
    
                    // Invoke factory processors registered as beans in the context.
                    invokeBeanFactoryPostProcessors(beanFactory);
    
                    // Register bean processors that intercept bean creation.
                    // 在这里生成代理对象后处理器 AspectJAwareAdvisorAutoProxyCreator
                    registerBeanPostProcessors(beanFactory);
    
                    // Initialize message source for this context.
                    initMessageSource();
    
                    // Initialize event multicaster for this context.
                    initApplicationEventMulticaster();
    
                    // Initialize other special beans in specific context subclasses.
                    onRefresh();
    
                    // Check for listener beans and register them.
                    registerListeners();
    
                    // Instantiate all remaining (non-lazy-init) singletons.
                    finishBeanFactoryInitialization(beanFactory);
    
                    // Last step: publish corresponding event.
                    finishRefresh();
                }

    接下来进入方法:registerBeanPostProcessors(beanFactory)

        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(beanFactory, priorityOrderedPostProcessors);
            registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    
            // Next, register the BeanPostProcessors that implement Ordered.
            List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
            for (String ppName : orderedPostProcessorNames) {
                //AspectJAwareAdvisorAutoProxyCreator的实例化就是在这里进行的
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                orderedPostProcessors.add(pp);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    internalPostProcessors.add(pp);
                }
            }
            sortPostProcessors(beanFactory, orderedPostProcessors);
            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(beanFactory, internalPostProcessors);
            registerBeanPostProcessors(beanFactory, internalPostProcessors);
    
            beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
        }

     截图如下:

    二.userDao的实例化过程
    目标对象userDao的实例化过程中初始化方法initializeBean过程中 上个阶段生成的AspectJAwareAdvisorAutoProxyCreator对象就会起作用
    先进入AbstractAutowireCapableBeanFactory的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()) {
    // 调用bean后处理器---before
    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()) {
    //调用bean后处理器---After 代理对象的生成在这个方法中进行的
    wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
    }

     进入AbstractAutoProxyCreator的postProcessAfterInitialization方法

        /**
         * Create a proxy with the configured interceptors if the bean is
         * identified as one to proxy by the subclass.
         * @see #getAdvicesAndAdvisorsForBean
         */
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean != null) {
                Object cacheKey = getCacheKey(bean.getClass(), beanName);
                if (!this.earlyProxyReferences.contains(cacheKey)) {
                    // 代理对象在此方法中生成
                    return wrapIfNecessary(bean, beanName, cacheKey);
                }
            }
            return bean;
        }

     进入wrapIfNecessary方法

        /**
         * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
         * @param bean the raw bean instance
         * @param beanName the name of the bean
         * @param cacheKey the cache key for metadata access
         * @return a proxy wrapping the bean, or the raw bean instance as-is
         */
        protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
            // 先对bean做一些过滤 对于不需要生成代理对象的bean进行返回
            if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
                return bean;
            }
            if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
                return bean;
            }
            if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return bean;
            }
    
            // Create proxy if we have advice.
            // 获取bean所有匹配的增强器
            Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
            if (specificInterceptors != DO_NOT_PROXY) {
                this.advisedBeans.put(cacheKey, Boolean.TRUE);
                // 生成代理对象
                Object proxy = createProxy(
                        bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
                this.proxyTypes.put(cacheKey, proxy.getClass());
                // 将生成的代理对象放入容器中,此时beanName对应的bean是生成的代理对象,不在是原来的bean
                return proxy;
            }
    
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }

    接下来进行分析

    getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null)和
    createProxy

     先进入getAdvicesAndAdvisorsForBean方法;

        @Override
        protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
            //进入该方法
            List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
            if (advisors.isEmpty()) {
                return DO_NOT_PROXY;
            }
            return advisors.toArray();
        }
        protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
            // 查找所有的增加器
            List<Advisor> candidateAdvisors = findCandidateAdvisors();
            // 查找该beanClass匹配的增强器
            List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
            extendAdvisors(eligibleAdvisors);
            if (!eligibleAdvisors.isEmpty()) {
                eligibleAdvisors = sortAdvisors(eligibleAdvisors);
            }
            return eligibleAdvisors;
        }


    2.代理对象的生成过程,有JDK动态代理和cglib两种生成方式,默认是JDK动态代理
    在代理对象生成的时候回进行判断,如果是对接口进行代理是使用JDK代理,如果是对类进行代理则使用CGLIB进行代理

        protected Object createProxy(
                Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
    
            if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
                AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
            }
    
            ProxyFactory proxyFactory = new ProxyFactory();
            proxyFactory.copyFrom(this);
    
            if (!proxyFactory.isProxyTargetClass()) {
                if (shouldProxyTargetClass(beanClass, beanName)) {
                    proxyFactory.setProxyTargetClass(true);
                }
                else {
                    evaluateProxyInterfaces(beanClass, proxyFactory);
                }
            }
            //获取所有的通知器,并给ProxyFactory配置通知器和目标对象
            Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
            for (Advisor advisor : advisors) {
                proxyFactory.addAdvisor(advisor);
            }
    
            proxyFactory.setTargetSource(targetSource);
            customizeProxyFactory(proxyFactory);
    
            proxyFactory.setFrozen(this.freezeProxy);
            if (advisorsPreFiltered()) {
                proxyFactory.setPreFiltered(true);
            }
            // 代理对象的生成
            return proxyFactory.getProxy(getProxyClassLoader());
        }

     ProxyFactory对象继承ProxyCreatorSupport,所有回调用ProxyCreatorSupport的方法

        public Object getProxy(ClassLoader classLoader) {
            // 下面的createAopProxy()方法是ProxyCreatorSupport类中的方法
            if (!this.active) {
                activate();
            }
            return createAopProxy().getProxy(classLoader);
        }

     下面进入

    createAopProxy方法
        @Override
        public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
            if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
                Class<?> targetClass = config.getTargetClass();
                if (targetClass == null) {
                    throw new AopConfigException("TargetSource cannot determine target class: " +
                            "Either an interface or a target is required for proxy creation.");
                }
                // 如果代理的对象是接口 则使用JDK代理,否则使用CGLIB代理
                if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                    return new JdkDynamicAopProxy(config);
                }
                
                return new ObjenesisCglibAopProxy(config);
            }
            else {
                // 默认是使用JDK代理
                return new JdkDynamicAopProxy(config);
            }
        }
  • 相关阅读:
    java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
    JAVA日期处理(Timestamp)
    使用JS截取字符串函数详解
    jQuery获取select option
    JAVA获取oracle中sequences的最后一个值
    <s:iterator> 序号
    Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法总结
    zjoi2018day1 游记
    hihocoder 后缀自动机五·重复旋律8 求循环同构串出现的次数
    hihocoder 1457 后缀自动机四·重复旋律7 求不同子串的和
  • 原文地址:https://www.cnblogs.com/histlyb/p/9483120.html
Copyright © 2011-2022 走看看