首页 > 编程语言 > 详细

Spring AOP 实现原理

时间:2021-02-03 23:32:21      阅读:35      评论:0      收藏:0      [点我收藏+]


//
AbstractBeanFactory public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args) throws BeansException { return this.doGetBean(name, requiredType, args, false); } //getSingleton //AbstractAutowireCapableBeanFactory public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; Object current; for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) { BeanPostProcessor processor = (BeanPostProcessor)var4.next(); current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } } return result; }

 

Spring AOP 原理:

默认的策略是如果目标类是接口,则使用JDK动态代理技术,否则使用Cglib来生成代理。如果指定了@EnableAspectJAutoProxy(proxyTargetClass = true) 则使用Cglib代理,在Spring Bean处理器的AspectJAwareAdvisorAutoProxyCreator创建的代理对象

getBean——>AbstractBeanFactory:doGetBean->
AbstractAutowireCapableBeanFactory:createBean->doCreateBean->
initializeBean:applyBeanPostProcessorsAfterInitialization->AbstractAutoProxyCreator:AnnotationAwareAspectJAutoProxyCreator(后置处理器):
wrapIfNecessary:createProxy->ProxyCreatorSupport:createAopProxy
Object sharedInstance = this.getSingleton(beanName);
AbstractAutowireCapableBeanFactory AbstractAutowireCapableBeanFactory——》createBean
doCreateBean-> initializeBean->applyBeanPostProcessorsAfterInitialization
applyBeanPostProcessorsAfterInitialization 后置处理器里面创建的代理对象
this.getBeanPostProcessors() spring 的处理器 有7个处理器
AbstractAdvisingBeanPostProcessor 后置处理器 applyBeanPostProcessorsAfterInitialization
proxyFactory.getProxy(this.getProxyClassLoader());
applyBeanPostProcessorsAfterInitialization
处理器:AspectJAwareAdvisorAutoProxyCreator_>AbstractAutoProxyCreator:postProcessAfterInitialization
wrapIfNecessary:createProxy->proxyFactory.getProxy(this.getProxyClassLoader());
AnnotationAwareAspectJAutoProxyCreator
完成代理 DefaultAopProxyFactory

proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false
 protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        BeanWrapper instanceWrapper = null;
       // 删除无关代码
        Object exposedObject = bean;

        try {
            this.populateBean(beanName, mbd, instanceWrapper);
            // 创建代理入口
            exposedObject = this.initializeBean(beanName, exposedObject, mbd);
        } catch (Throwable var18) {
            if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
                throw (BeanCreationException)var18;
            }
 
    }

 



AbstractAutoProxyCreator
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
//创建代理入库
return this.wrapIfNecessary(bean, beanName, cacheKey); } } return bean; }

 

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(() -> {
                this.invokeAwareMethods(beanName, bean);
                return null;
            }, this.getAccessControlContext());
        } else {
            this.invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        }

        try {
            this.invokeInitMethods(beanName, wrappedBean, mbd);
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
        }
         //bean 是否已经创建了?

        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }

 

//AbstractAutowireCapableBeanFactory bean的处理器

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

        Object current;
//this.getBeanPostProcessors() debug这个代码发现 有如下图 7个处理器
for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) { BeanPostProcessor processor = (BeanPostProcessor)var4.next(); current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } } return result; }

技术分享图片

 protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
        if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
            return bean;
        } else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
            return bean;
        } else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {
            Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
            if (specificInterceptors != DO_NOT_PROXY) {
                this.advisedBeans.put(cacheKey, Boolean.TRUE);
//创建代理入口 Object proxy
= this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } else { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } } else { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } }

AbstractAutoProxyCreator

//  AbstractAutoProxyCreator
 protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable 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 (this.shouldProxyTargetClass(beanClass, beanName)) {
                proxyFactory.setProxyTargetClass(true);
            } else {
                this.evaluateProxyInterfaces(beanClass, proxyFactory);
            }
        }

        Advisor[] advisors = this.buildAdvisors(beanName, specificInterceptors);
        proxyFactory.addAdvisors(advisors);
        proxyFactory.setTargetSource(targetSource);
        this.customizeProxyFactory(proxyFactory);
        proxyFactory.setFrozen(this.freezeProxy);
        if (this.advisorsPreFiltered()) {
            proxyFactory.setPreFiltered(true);
        }

       //从工厂里面获取proxyFactory
        return proxyFactory.getProxy(this.getProxyClassLoader());
    }

//ProxyFactory
  public Object getProxy(@Nullable ClassLoader classLoader) {
        return this.createAopProxy().getProxy(classLoader);
    }
//ProxyCreatorSupport
  protected final synchronized AopProxy createAopProxy() {
        if (!this.active) {
            this.activate();
        }

        return this.getAopProxyFactory().createAopProxy(this);
    }
//ProxyCreatorSupport 
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
     //设置了@EnableAspectJAutoProxy(proxyTargetClass = false)默认为false false则使用Jdk代理 并且  实现了接口 使用JDK代理
        if (!config.isOptimize() && !config.isProxyTargetClass() && !this.hasNoUserSuppliedProxyInterfaces(config)) {
            return new JdkDynamicAopProxy(config);
        } else {
            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.");
            } else {
        //再次判断是JDK 还是CGlib代理
                return (AopProxy)(!targetClass.isInterface() && !Proxy.isProxyClass(targetClass) ? new ObjenesisCglibAopProxy(config) : new JdkDynamicAopProxy(config));
            }
        }
    }
//JdkDynamicAopProxy
  public Object getProxy(@Nullable ClassLoader classLoader) {
        
        Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
        this.findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
//调用实际调用创建代理对象
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); } //Proxy 使用JDK自带的 创建代理对象 private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager Constructor<?> cons, InvocationHandler h) { try { if (caller != null) { checkNewProxyPermission(caller, cons.getDeclaringClass()); } //创建代理对象 return cons.newInstance(new Object[]{h}); } catch (IllegalAccessException | InstantiationException e) { //删除部分无关代码 } }

 

 

技术分享图片

 

 

 

 

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

        Object current;
        for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
            BeanPostProcessor processor = (BeanPostProcessor)var4.next();
            current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) {
                return result;
            }
        }

        return result;
    }

 

Spring bean处理器有7个,Aop代理在AspectJAwareAdvisorAutoProxyCreator 里面完成的创建代理对象

 技术分享图片

 

 

技术分享图片

 


 

Spring AOP 实现原理

原文:https://www.cnblogs.com/fanBlog/p/13419797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!