前言java
前面寫了六篇文章詳細地分析了Spring Bean加載流程,這部分完了以後就要進入一個比較困難的部分了,就是AOP的實現原理分析。爲了探究AOP實現原理,首先定義幾個類,一個Dao接口:node
1 public interface Dao { 2 3 public void select(); 4 5 public void insert(); 6 7 }
Dao接口的實現類DaoImpl:spring
1 public class DaoImpl implements Dao { 2 3 @Override 4 public void select() { 5 System.out.println("Enter DaoImpl.select()"); 6 } 7 8 @Override 9 public void insert() { 10 System.out.println("Enter DaoImpl.insert()"); 11 } 12 13 }
定義一個TimeHandler,用於方法調用先後打印時間,在AOP中,這扮演的是橫切關注點的角色:express
1 public class TimeHandler { 2 3 public void printTime() { 4 System.out.println("CurrentTime:" + System.currentTimeMillis()); 5 } 6 7 }
定義一個XML文件aop.xml:dom
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/aop 9 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 10 11 <bean id="daoImpl" class="org.xrq.action.aop.DaoImpl" /> 12 <bean id="timeHandler" class="org.xrq.action.aop.TimeHandler" /> 13 14 <aop:config proxy-target-class="true"> 15 <aop:aspect id="time" ref="timeHandler"> 16 <aop:pointcut id="addAllMethod" expression="execution(* org.xrq.action.aop.Dao.*(..))" /> 17 <aop:before method="printTime" pointcut-ref="addAllMethod" /> 18 <aop:after method="printTime" pointcut-ref="addAllMethod" /> 19 </aop:aspect> 20 </aop:config> 21 22 </beans>
寫一段測試代碼TestAop.java:ide
1 public class TestAop { 2 3 @Test 4 public void testAop() { 5 ApplicationContext ac = new ClassPathXmlApplicationContext("spring/aop.xml"); 6 7 Dao dao = (Dao)ac.getBean("daoImpl"); 8 dao.select(); 9 } 10 11 }
代碼運行結果就不看了,有了以上的內容,咱們就能夠根據這些跟一下代碼,看看Spring究竟是如何實現AOP的。工具
AOP實現原理----找到Spring處理AOP的源頭oop
有不少朋友不肯意去看AOP源碼的一個很大緣由是由於找不到AOP源碼實現的入口在哪裏,這個確實是。不過咱們能夠看一下上面的測試代碼,就普通Bean也好、AOP也好,最終都是經過getBean方法獲取到Bean並調用方法的,getBean以後的對象已經先後都打印了TimeHandler類printTime()方法裏面的內容,能夠想見它們已是被Spring容器處理過了。測試
既然如此,那無非就兩個地方處理:this
所以,本文圍繞【1.加載Bean定義的時候應該有過特殊的處理】展開,先找一下究竟是哪裏Spring對AOP作了特殊的處理。代碼直接定位到DefaultBeanDefinitionDocumentReader的parseBeanDefinitions方法:
1 protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { 2 if (delegate.isDefaultNamespace(root)) { 3 NodeList nl = root.getChildNodes(); 4 for (int i = 0; i < nl.getLength(); i++) { 5 Node node = nl.item(i); 6 if (node instanceof Element) { 7 Element ele = (Element) node; 8 if (delegate.isDefaultNamespace(ele)) { 9 parseDefaultElement(ele, delegate); 10 } 11 else { 12 delegate.parseCustomElement(ele); 13 } 14 } 15 } 16 } 17 else { 18 delegate.parseCustomElement(root); 19 } 20 }
正常來講,遇到<bean id="daoImpl"...>、<bean id="timeHandler"...>這兩個標籤的時候,都會執行第9行的代碼,由於<bean>標籤是默認的Namespace。可是在遇到後面的<aop:config>標籤的時候就不同了,<aop:config>並非默認的Namespace,所以會執行第12行的代碼,看一下:
1 public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) { 2 String namespaceUri = getNamespaceURI(ele); 3 NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); 4 if (handler == null) { 5 error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele); 6 return null; 7 } 8 return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd)); 9 }
由於以前把整個XML解析爲了org.w3c.dom.Document,org.w3c.dom.Document以樹的形式表示整個XML,具體到每個節點就是一個Node。
首先第2行從<aop:config>這個Node(參數Element是Node接口的子接口)中拿到Namespace="http://www.springframework.org/schema/aop",第3行的代碼根據這個Namespace獲取對應的NamespaceHandler即Namespace處理器,具體到aop這個Namespace的NamespaceHandler是org.springframework.aop.config.AopNamespaceHandler類,也就是第3行代碼獲取到的結果。具體到AopNamespaceHandler裏面,有幾個Parser,是用於具體標籤轉換的,分別爲:
接着,就是第8行的代碼,利用AopNamespaceHandler的parse方法,解析<aop:config>下的內容了。
AOP Bean定義加載----根據織入方式將<aop:before>、<aop:after>轉換成名爲adviceDef的RootBeanDefinition
上面通過分析,已經找到了Spring是經過AopNamespaceHandler處理的AOP,那麼接着進入AopNamespaceHandler的parse方法源代碼:
1 public BeanDefinition parse(Element element, ParserContext parserContext) { 2 return findParserForElement(element, parserContext).parse(element, parserContext); 3 }
首先獲取具體的Parser,由於當前節點是<aop:config>,上一部分最後有列,config是經過ConfigBeanDefinitionParser來處理的,所以findParserForElement(element, parserContext)這一部分代碼獲取到的是ConfigBeanDefinitionParser,接着看ConfigBeanDefinitionParser的parse方法:
1 public BeanDefinition parse(Element element, ParserContext parserContext) { 2 CompositeComponentDefinition compositeDef = 3 new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); 4 parserContext.pushContainingComponent(compositeDef); 5 6 configureAutoProxyCreator(parserContext, element); 7 8 List<Element> childElts = DomUtils.getChildElements(element); 9 for (Element elt: childElts) { 10 String localName = parserContext.getDelegate().getLocalName(elt); 11 if (POINTCUT.equals(localName)) { 12 parsePointcut(elt, parserContext); 13 } 14 else if (ADVISOR.equals(localName)) { 15 parseAdvisor(elt, parserContext); 16 } 17 else if (ASPECT.equals(localName)) { 18 parseAspect(elt, parserContext); 19 } 20 } 21 22 parserContext.popAndRegisterContainingComponent(); 23 return null; 24 }
重點先提一下第6行的代碼,該行代碼的具體實現不跟了但它很是重要,configureAutoProxyCreator方法的做用我用幾句話說一下:
<aop:config>下的節點爲<aop:aspect>,想見必然是執行第18行的代碼parseAspect,跟進去:
1 private void parseAspect(Element aspectElement, ParserContext parserContext) { 2 String aspectId = aspectElement.getAttribute(ID); 3 String aspectName = aspectElement.getAttribute(REF); 4 5 try { 6 this.parseState.push(new AspectEntry(aspectId, aspectName)); 7 List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>(); 8 List<BeanReference> beanReferences = new ArrayList<BeanReference>(); 9 10 List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS); 11 for (int i = METHOD_INDEX; i < declareParents.size(); i++) { 12 Element declareParentsElement = declareParents.get(i); 13 beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext)); 14 } 15 16 // We have to parse "advice" and all the advice kinds in one loop, to get the 17 // ordering semantics right. 18 NodeList nodeList = aspectElement.getChildNodes(); 19 boolean adviceFoundAlready = false; 20 for (int i = 0; i < nodeList.getLength(); i++) { 21 Node node = nodeList.item(i); 22 if (isAdviceNode(node, parserContext)) { 23 if (!adviceFoundAlready) { 24 adviceFoundAlready = true; 25 if (!StringUtils.hasText(aspectName)) { 26 parserContext.getReaderContext().error( 27 "<aspect> tag needs aspect bean reference via 'ref' attribute when declaring advices.", 28 aspectElement, this.parseState.snapshot()); 29 return; 30 } 31 beanReferences.add(new RuntimeBeanReference(aspectName)); 32 } 33 AbstractBeanDefinition advisorDefinition = parseAdvice( 34 aspectName, i, aspectElement, (Element) node, parserContext, beanDefinitions, beanReferences); 35 beanDefinitions.add(advisorDefinition); 36 } 37 } 38 39 AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition( 40 aspectElement, aspectId, beanDefinitions, beanReferences, parserContext); 41 parserContext.pushContainingComponent(aspectComponentDefinition); 42 43 List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT); 44 for (Element pointcutElement : pointcuts) { 45 parsePointcut(pointcutElement, parserContext); 46 } 47 48 parserContext.popAndRegisterContainingComponent(); 49 } 50 finally { 51 this.parseState.pop(); 52 } 53 }
從第20行~第37行的循環開始關注這個方法。這個for循環有一個關鍵的判斷就是第22行的ifAdviceNode判斷,看下ifAdviceNode方法作了什麼:
1 private boolean isAdviceNode(Node aNode, ParserContext parserContext) { 2 if (!(aNode instanceof Element)) { 3 return false; 4 } 5 else { 6 String name = parserContext.getDelegate().getLocalName(aNode); 7 return (BEFORE.equals(name) || AFTER.equals(name) || AFTER_RETURNING_ELEMENT.equals(name) || 8 AFTER_THROWING_ELEMENT.equals(name) || AROUND.equals(name)); 9 } 10 }
即這個for循環只用來處理<aop:aspect>標籤下的<aop:before>、<aop:after>、<aop:after-returning>、<aop:after-throwing method="">、<aop:around method="">這五個標籤的。
接着,若是是上述五種標籤之一,那麼進入第33行~第34行的parseAdvice方法:
1 private AbstractBeanDefinition parseAdvice( 2 String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext, 3 List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) { 4 5 try { 6 this.parseState.push(new AdviceEntry(parserContext.getDelegate().getLocalName(adviceElement))); 7 8 // create the method factory bean 9 RootBeanDefinition methodDefinition = new RootBeanDefinition(MethodLocatingFactoryBean.class); 10 methodDefinition.getPropertyValues().add("targetBeanName", aspectName); 11 methodDefinition.getPropertyValues().add("methodName", adviceElement.getAttribute("method")); 12 methodDefinition.setSynthetic(true); 13 14 // create instance factory definition 15 RootBeanDefinition aspectFactoryDef = 16 new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class); 17 aspectFactoryDef.getPropertyValues().add("aspectBeanName", aspectName); 18 aspectFactoryDef.setSynthetic(true); 19 20 // register the pointcut 21 AbstractBeanDefinition adviceDef = createAdviceDefinition( 22 adviceElement, parserContext, aspectName, order, methodDefinition, aspectFactoryDef, 23 beanDefinitions, beanReferences); 24 25 // configure the advisor 26 RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class); 27 advisorDefinition.setSource(parserContext.extractSource(adviceElement)); 28 advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef); 29 if (aspectElement.hasAttribute(ORDER_PROPERTY)) { 30 advisorDefinition.getPropertyValues().add( 31 ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY)); 32 } 33 34 // register the final advisor 35 parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition); 36 37 return advisorDefinition; 38 } 39 finally { 40 this.parseState.pop(); 41 } 42 }
方法主要作了三件事:
下面來看作的第一件事createAdviceDefinition方法定義:
1 private AbstractBeanDefinition createAdviceDefinition( 2 Element adviceElement, ParserContext parserContext, String aspectName, int order, 3 RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef, 4 List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) { 5 6 RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement, parserContext)); 7 adviceDefinition.setSource(parserContext.extractSource(adviceElement)); 8 adviceDefinition.getPropertyValues().add(ASPECT_NAME_PROPERTY, aspectName); 9 adviceDefinition.getPropertyValues().add(DECLARATION_ORDER_PROPERTY, order); 10 11 if (adviceElement.hasAttribute(RETURNING)) { 12 adviceDefinition.getPropertyValues().add( 13 RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING)); 14 } 15 if (adviceElement.hasAttribute(THROWING)) { 16 adviceDefinition.getPropertyValues().add( 17 THROWING_PROPERTY, adviceElement.getAttribute(THROWING)); 18 } 19 if (adviceElement.hasAttribute(ARG_NAMES)) { 20 adviceDefinition.getPropertyValues().add( 21 ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES)); 22 } 23 24 ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues(); 25 cav.addIndexedArgumentValue(METHOD_INDEX, methodDef); 26 27 Object pointcut = parsePointcutProperty(adviceElement, parserContext); 28 if (pointcut instanceof BeanDefinition) { 29 cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut); 30 beanDefinitions.add((BeanDefinition) pointcut); 31 } 32 else if (pointcut instanceof String) { 33 RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut); 34 cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef); 35 beanReferences.add(pointcutRef); 36 } 37 38 cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef); 39 40 return adviceDefinition; 41 }
首先能夠看到,建立的AbstractBeanDefinition實例是RootBeanDefinition,這和普通Bean建立的實例爲GenericBeanDefinition不一樣。而後進入第6行的getAdviceClass方法看一下:
1 private Class getAdviceClass(Element adviceElement, ParserContext parserContext) { 2 String elementName = parserContext.getDelegate().getLocalName(adviceElement); 3 if (BEFORE.equals(elementName)) { 4 return AspectJMethodBeforeAdvice.class; 5 } 6 else if (AFTER.equals(elementName)) { 7 return AspectJAfterAdvice.class; 8 } 9 else if (AFTER_RETURNING_ELEMENT.equals(elementName)) { 10 return AspectJAfterReturningAdvice.class; 11 } 12 else if (AFTER_THROWING_ELEMENT.equals(elementName)) { 13 return AspectJAfterThrowingAdvice.class; 14 } 15 else if (AROUND.equals(elementName)) { 16 return AspectJAroundAdvice.class; 17 } 18 else { 19 throw new IllegalArgumentException("Unknown advice kind [" + elementName + "]."); 20 } 21 }
既然建立Bean定義,必然該Bean定義中要對應一個具體的Class,不一樣的切入方式對應不一樣的Class:
createAdviceDefinition方法剩餘邏輯沒什麼,就是判斷一下標籤裏面的屬性並設置一下相應的值而已,至此<aop:before>、<aop:after>兩個標籤對應的AbstractBeanDefinition就建立出來了。
AOP Bean定義加載----將名爲adviceDef的RootBeanDefinition轉換成名爲advisorDefinition的RootBeanDefinition
下面咱們看一下第二步的操做,將名爲adviceDef的RootBeanD轉換成名爲advisorDefinition的RootBeanDefinition,跟一下上面一部分ConfigBeanDefinitionParser類parseAdvice方法的第26行~32行的代碼:
1 RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class); 2 advisorDefinition.setSource(parserContext.extractSource(adviceElement)); 3 advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef); 4 if (aspectElement.hasAttribute(ORDER_PROPERTY)) { 5 advisorDefinition.getPropertyValues().add( 6 ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY)); 7 }
這裏至關於將上一步生成的RootBeanDefinition包裝了一下,new一個新的RootBeanDefinition出來,Class類型是org.springframework.aop.aspectj.AspectJPointcutAdvisor。
第4行~第7行的代碼是用於判斷<aop:aspect>標籤中有沒有"order"屬性的,有就設置一下,"order"屬性是用來控制切入方法優先級的。
AOP Bean定義加載----將BeanDefinition註冊到DefaultListableBeanFactory中
最後一步就是將BeanDefinition註冊到DefaultListableBeanFactory中了,代碼就是前面ConfigBeanDefinitionParser的parseAdvice方法的最後一部分了:
1 ... 2 // register the final advisor 3 parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition); 4 ...
跟一下registerWithGeneratedName方法的實現:
1 public String registerWithGeneratedName(BeanDefinition beanDefinition) { 2 String generatedName = generateBeanName(beanDefinition); 3 getRegistry().registerBeanDefinition(generatedName, beanDefinition); 4 return generatedName; 5 }
第2行獲取註冊的名字BeanName,和<bean>的註冊差很少,使用的是Class全路徑+"#"+全局計數器的方式,其中的Class全路徑爲org.springframework.aop.aspectj.AspectJPointcutAdvisor,依次類推,每個BeanName應當爲org.springframework.aop.aspectj.AspectJPointcutAdvisor#0、org.springframework.aop.aspectj.AspectJPointcutAdvisor#一、org.springframework.aop.aspectj.AspectJPointcutAdvisor#2這樣下去。
第3行向DefaultListableBeanFactory中註冊,BeanName已經有了,剩下的就是Bean定義,Bean定義的解析流程以前已經看過了,就不說了。
AOP Bean定義加載----AopNamespaceHandler處理<aop:pointcut>流程
回到ConfigBeanDefinitionParser的parseAspect方法:
1 private void parseAspect(Element aspectElement, ParserContext parserContext) { 2 3 ... 4 5 AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition( 6 aspectElement, aspectId, beanDefinitions, beanReferences, parserContext); 7 parserContext.pushContainingComponent(aspectComponentDefinition); 8 9 List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT); 10 for (Element pointcutElement : pointcuts) { 11 parsePointcut(pointcutElement, parserContext); 12 } 13 14 parserContext.popAndRegisterContainingComponent(); 15 } 16 finally { 17 this.parseState.pop(); 18 } 19 }
省略號部分表示是解析的是<aop:before>、<aop:after>這種標籤,上部分已經說過了,就不說了,下面看一下解析<aop:pointcut>部分的源碼。
第5行~第7行的代碼構建了一個Aspect標籤組件定義,並將Apsect標籤組件定義推到ParseContext即解析工具上下文中,這部分代碼不是關鍵。
第9行的代碼拿到全部<aop:aspect>下的pointcut標籤,進行遍歷,由parsePointcut方法進行處理:
1 private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) { 2 String id = pointcutElement.getAttribute(ID); 3 String expression = pointcutElement.getAttribute(EXPRESSION); 4 5 AbstractBeanDefinition pointcutDefinition = null; 6 7 try { 8 this.parseState.push(new PointcutEntry(id)); 9 pointcutDefinition = createPointcutDefinition(expression); 10 pointcutDefinition.setSource(parserContext.extractSource(pointcutElement)); 11 12 String pointcutBeanName = id; 13 if (StringUtils.hasText(pointcutBeanName)) { 14 parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition); 15 } 16 else { 17 pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition); 18 } 19 20 parserContext.registerComponent( 21 new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression)); 22 } 23 finally { 24 this.parseState.pop(); 25 } 26 27 return pointcutDefinition; 28 }
第2行~第3行的代碼獲取<aop:pointcut>標籤下的"id"屬性與"expression"屬性。
第8行的代碼推送一個PointcutEntry,表示當前Spring上下文正在解析Pointcut標籤。
第9行的代碼建立Pointcut的Bean定義,以後再看,先把其餘方法都看一下。
第10行的代碼無論它,最終從NullSourceExtractor的extractSource方法獲取Source,就是個null。
第12行~第18行的代碼用於註冊獲取到的Bean定義,默認pointcutBeanName爲<aop:pointcut>標籤中定義的id屬性:
第20行~第21行的代碼向解析工具上下文中註冊一個Pointcut組件定義
第23行~第25行的代碼,finally塊在<aop:pointcut>標籤解析完畢後,讓以前推送至棧頂的PointcutEntry出棧,表示這次<aop:pointcut>標籤解析完畢。
最後回頭來一下第9行代碼createPointcutDefinition的實現,比較簡單:
1 protected AbstractBeanDefinition createPointcutDefinition(String expression) { 2 RootBeanDefinition beanDefinition = new RootBeanDefinition(AspectJExpressionPointcut.class); 3 beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE); 4 beanDefinition.setSynthetic(true); 5 beanDefinition.getPropertyValues().add(EXPRESSION, expression); 6 return beanDefinition; 7 }
關鍵就是注意一下兩點:
這樣一個流程下來,就解析了<aop:pointcut>標籤中的內容並將之轉換爲RootBeanDefintion存儲在Spring容器中。