1. 程式人生 > 其它 >Spring AOP原始碼解析

Spring AOP原始碼解析

一、@EnableAspectJAutoProxy註解
在主配置類中新增@EnableAspectJAutoProxy註解,開啟aop支援,那麼@EnableAspectJAutoProxy到底做了什麼?接下來分析下:

@EnableAspectJAutoProxy點進去如下:

此時看到了我們非常熟悉的@Import註解,@Import(AspectJAutoProxyRegistrar.class),進入到AspectJAutoProxyRegistrar發現實現了ImportBeanDefinitionRegistrar如下:

class AspectJAutoProxyRegistrar implements
ImportBeanDefinitionRegistrar { /** * Register, escalate, and configure the AspectJ auto proxy creator based on the value * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing * {@code @Configuration} class. */ @Override public void registerBeanDefinitions( AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry); AnnotationAttributes enableAspectJAutoProxy
= AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class); if (enableAspectJAutoProxy != null) { if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) { AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); }
if (enableAspectJAutoProxy.getBoolean("exposeProxy")) { AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry); } } } }

會呼叫registerBeanDefinitions方法,跟進到這個方法裡面,主要作用就是往Spring容器中註冊AnnotationAwareAspectJAutoProxyCreator的Bean的定義資訊:

郭慕榮部落格園