1. 程式人生 > >Spring--AOP 例子

Spring--AOP 例子

結束 oaf signature 日誌 類加載器 lis 能說 ssi system

先用代碼講一下什麽是傳統的AOP(面向切面編程)編程

需求:實現一個簡單的計算器,在每一步的運算前添加日誌。最傳統的方式如下:

Calculator.Java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.calculator;
  2. /**
  3. * Created by Limbo on 16/7/14.
  4. */
  5. public interface Calculator {
  6. int add(int i , int j);
  7. int sub(int i , int j);
  8. int mul(int i , int j);
  9. int div(int i , int j);
  10. }

CalculatorImpl.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.calculator;
  2. /**
  3. * Created by Limbo on 16/7/14.
  4. */
  5. public class CalculatorImpl implements Calculator {
  6. @Override
  7. public int add(int i, int j) {
  8. System.out.println("The method add begin with [ "+ i +"," + j+" ]");
  9. System.out.println("The method add end with [ "+ i +"," + j+"]");
  10. return i + j;
  11. }
  12. @Override
  13. public int sub(int i, int j) {
  14. System.out.println("The method sub begin with [ "+ i +"," + j+" ]");
  15. System.out.println("The method sub end with [ "+ i +"," + j+" ]");
  16. return i - j;
  17. }
  18. @Override
  19. public int mul(int i, int j) {
  20. System.out.println("The method mul begin with [ "+ i +"," + j+" ]");
  21. System.out.println("The method mul end with [ "+ i +"," + j+" ]");
  22. return i * j;
  23. }
  24. @Override
  25. public int div(int i, int j) {
  26. System.out.println("The method div begin with [ "+ i +"," + j+" ]");
  27. System.out.println("The method div end with [ "+ i +"," + j+" ]");
  28. return i / j;
  29. }
  30. }

這樣就完成了需求,但是我們發現,倘若是要修改日誌的信息,那麽就需要在具體方法裏面改,這樣做很麻煩,而且把原本清爽的方法改的十分混亂,方法應該表現的是核心功能,而不是這些無關緊要的關註點,下面用原生的java的方式實現在執行方法時,動態添加輸出日誌方法

CalculatorImpl.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.calculator;
  2. /**
  3. * Created by Limbo on 16/7/14.
  4. */
  5. public class CalculatorImpl implements Calculator {
  6. @Override
  7. public int add(int i, int j) {
  8. return i + j;
  9. }
  10. @Override
  11. public int sub(int i, int j) {
  12. return i - j;
  13. }
  14. @Override
  15. public int mul(int i, int j) {
  16. return i * j;
  17. }
  18. @Override
  19. public int div(int i, int j) {
  20. return i / j;
  21. }
  22. }


CalculatorLoggingProxy.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.calculator;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. import java.util.Arrays;
  6. import java.util.Objects;
  7. /**
  8. * Created by Limbo on 16/7/14.
  9. */
  10. public class CalculatorLoggingProxy {
  11. //要代理的對象
  12. private Calculator target;
  13. public CalculatorLoggingProxy(Calculator target) {
  14. this.target = target;
  15. }
  16. public Calculator getLoggingProxy(){
  17. //代理對象由哪一個類加載器負責加載
  18. ClassLoader loader = target.getClass().getClassLoader();
  19. //代理對象的類型,即其中有哪些方法
  20. Class[] interfaces = new Class[]{Calculator.class};
  21. // 當調用代理對象其中的方法時,執行改代碼
  22. InvocationHandler handler = new InvocationHandler() {
  23. @Override
  24. /**
  25. * proxy:正在返回的那個對象的代理,一般情況下,在invoke方法中不使用該對象
  26. * method:正在被調用的方法
  27. * args:調用方法時,傳入的參數
  28. */
  29. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  30. String methodName = method.getName();
  31. System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
  32. //日誌
  33. Object result = method.invoke(target,args);
  34. System.out.println("The method " + methodName + " ends with " + result);
  35. return result;
  36. }
  37. };
  38. Calculator proxy = (Calculator) Proxy.newProxyInstance(loader,interfaces,handler);
  39. return proxy;
  40. }
  41. }


Main.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.calculator;
  2. /**
  3. * Created by Limbo on 16/7/14.
  4. */
  5. public class Main {
  6. public static void main(String[] args) {
  7. Calculator calculator = new CalculatorImpl();
  8. Calculator proxy = new CalculatorLoggingProxy(calculator).getLoggingProxy();
  9. int result = proxy.add(1,2);
  10. System.out.println("--->" + result);
  11. result = proxy.sub(1,2);
  12. System.out.println("--->" + result);
  13. result = proxy.mul(3,2);
  14. System.out.println("--->" + result);
  15. result = proxy.div(14,2);
  16. System.out.println("--->" + result);
  17. }
  18. }


這樣寫雖然已經簡化了代碼,而且可以任意修改日誌信息代碼,但是寫起來還是很麻煩!!!

下面我們使用spring自帶的aop包實現但是要加入

com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.8.5.RELEASE.jar

這兩個額外的包

下面看代碼,要點全部卸載代碼裏面了

Calculator.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.impl;
  2. /**
  3. * Created by Limbo on 16/7/14.
  4. */
  5. public interface Calculator {
  6. int add(int i, int j);
  7. int sub(int i, int j);
  8. int mul(int i, int j);
  9. int div(int i, int j);
  10. }

CalculatorImpl.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.impl;
  2. import org.springframework.stereotype.Component;
  3. /**
  4. * Created by Limbo on 16/7/14.
  5. */
  6. @Component("calculatorImpl")
  7. public class CalculatorImpl implements Calculator {
  8. @Override
  9. public int add(int i, int j) {
  10. return i + j;
  11. }
  12. @Override
  13. public int sub(int i, int j) {
  14. return i - j;
  15. }
  16. @Override
  17. public int mul(int i, int j) {
  18. return i * j;
  19. }
  20. @Override
  21. public int div(int i, int j) {
  22. return i / j;
  23. }
  24. }

LoggingAspect.java

[java] view plain copy print?
  1. package cn.limbo.spring.aop.impl;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.*;
  5. import org.springframework.core.annotation.Order;
  6. import org.springframework.stereotype.Component;
  7. import java.util.Arrays;
  8. import java.util.List;
  9. import java.util.Objects;
  10. /**
  11. * Created by Limbo on 16/7/14.
  12. */
  13. //把這個類聲明為切面:需要該類放入IOC容器中,再聲明為一個切面
  14. @Order(0)//指定切面優先級,只越小優先級越高
  15. @Aspect
  16. @Component
  17. public class LoggingAspect {
  18. /**
  19. * 定義一個方法,用於聲明切入點表達式,一般的,該方法中再不需要添加其他代碼
  20. * 主要是為了重用路徑,[email protected]
  21. * 後面的其他通知直接使用方法名來引用當前的切入點表達式
  22. */
  23. @Pointcut("execution(* cn.limbo.spring.aop.impl.Calculator.*(..))")
  24. public void declareJointPointExpression()
  25. {
  26. }
  27. //聲明該方法是一個前置通知:在目標方法之前執行
  28. @Before("declareJointPointExpression()")
  29. // @Before("execution(* cn.limbo.spring.aop.impl.*.*(..))") 該包下任意返回值,任意類,任意方法,任意參數類型
  30. public void beforeMethod(JoinPoint joinPoint)
  31. {
  32. String methodName = joinPoint.getSignature().getName();
  33. List<Object> args = Arrays.asList(joinPoint.getArgs());
  34. System.out.println("The Method "+ methodName+" Begins With " + args);
  35. }
  36. //在目標方法執行之後執行,無論這個方法是否出錯
  37. //在後置通知中還不能訪問目標方法的返回值,只能通過返回通知訪問
  38. @After("execution(* cn.limbo.spring.aop.impl.Calculator.*(int,int))")
  39. public void afterMethod(JoinPoint joinPoint)
  40. {
  41. String methodName = joinPoint.getSignature().getName();
  42. System.out.println("The Method "+ methodName+" Ends ");
  43. }
  44. /**
  45. * 在方法正常結束後執行的代碼
  46. * 返回通知是可以訪問到方法的返回值
  47. */
  48. @AfterReturning(value = "execution(* cn.limbo.spring.aop.impl.Calculator.*(..))",returning = "result")
  49. public void afterReturning(JoinPoint joinPoint , Object result)
  50. {
  51. String methodName = joinPoint.getSignature().getName();
  52. System.out.println("The Method " + methodName + " Ends With " + result);
  53. }
  54. /**
  55. *在目標方法出現異常的時候執行代碼
  56. * 可以訪問異常對象,且可以指定出現特定異常時再執行通知
  57. */
  58. @AfterThrowing(value = "execution(* cn.limbo.spring.aop.impl.Calculator.*(..))",throwing = "ex")
  59. public void afterThrowing(JoinPoint joinPoint,Exception ex)//Exception 可以改成 NullPointerException等特定異常
  60. {
  61. String methodName = joinPoint.getSignature().getName();
  62. System.out.println("The Method " + methodName + " Occurs With " + ex);
  63. }
  64. /**
  65. * 環繞通知需要ProceedingJoinPoint 類型參數 功能最強大
  66. * 環繞通知類似於動態代理的全過程:ProceedingJoinPoint 類型的參數可以決定是否執行目標方法
  67. * 且環繞通知必須有返回值,返回值即為目標方法的返回值
  68. */
  69. @Around("execution(* cn.limbo.spring.aop.impl.Calculator.*(..))")
  70. public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint)
  71. {
  72. Object result =null;
  73. String methodName = proceedingJoinPoint.getSignature().getName();
  74. try {
  75. //前置通知
  76. System.out.println("The Method " + methodName + " Begins With " + Arrays.asList(proceedingJoinPoint.getArgs()));
  77. result = proceedingJoinPoint.proceed();
  78. // 返回通知
  79. System.out.println("The Method " + methodName + " Ends With " + result);
  80. } catch (Throwable throwable) {
  81. //異常通知
  82. throwable.printStackTrace();
  83. }
  84. System.out.println("The Method " + methodName + " Ends ");
  85. return result;
  86. }
  87. }



applicationContext.xml

[html] view plain copy print?
  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:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  7. <!--配置自動掃描的包-->
  8. <context:component-scan base-package="cn.limbo.spring.aop.impl"></context:component-scan>
  9. <!--使Aspect註解起作用,自動為匹配的類生成代理對象-->
  10. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  11. </beans>

用xml來配置aop

application-config.xml

[html] view plain copy print?
  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 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  7. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
  8. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
  9. <bean id="userManager" class="com.tgb.aop.UserManagerImpl"/>
  10. <!--<bean id="aspcejHandler" class="com.tgb.aop.AspceJAdvice"/>-->
  11. <bean id="xmlHandler" class="com.tgb.aop.XMLAdvice" />
  12. <aop:config>
  13. <aop:aspect id="aspect" ref="xmlHandler">
  14. <aop:pointcut id="pointUserMgr" expression="execution(* com.tgb.aop.*.find*(..))"/>
  15. <aop:before method="doBefore" pointcut-ref="pointUserMgr"/>
  16. <aop:after method="doAfter" pointcut-ref="pointUserMgr"/>
  17. <aop:around method="doAround" pointcut-ref="pointUserMgr"/>
  18. <aop:after-returning method="doReturn" pointcut-ref="pointUserMgr"/>
  19. <aop:after-throwing method="doThrowing" throwing="ex" pointcut-ref="pointUserMgr"/>
  20. </aop:aspect>
  21. </aop:config>
  22. </beans>



一共有5類的通知,其中around最為強大,但是不一定最常用,aspect的底層實現都是通過代理來實現的,只能說這個輪子造的不錯

2016.12.09更新

最近在實際項目中配置aop發現了幾個問題,實際的項目配置的的模式是ssh即Spring4+SpringMVC+Hibernate4的模式。

基於註解的方式配置方式有些坑點:

1.發現SpringMVC中aop不起任何作用

經過排查和查找網上的資料,發現問題如下:

Spring MVC啟動時的配置文件,包含組件掃描、url映射以及設置freemarker參數,[email protected]設置?因為springmvc.xml與applicationContext.xml不是同時加載,如果不進行這樣的設置,那麽,[email protected],等到加載applicationContext.xml的時候,會因為容器已經存在Service類,使得cglib將不對Service進行代理,直接導致的結果就是在applicationContext 中的事務配置不起作用,發生異常時,無法對數據進行回滾。以上就是原因所在。

所以改進後的applicationContext.xml如下(只是更改自動掃描包的那個配置):

[html] view plain copy print?
  1. <context:component-scan base-package="cn.limbo">
  2. <!--不要將Controller掃進來,否則aop無法使用-->
  3. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  4. </context:component-scan>


spring-mvc.xml掃描包配置如下:

[html] view plain copy print?
  1. <context:component-scan base-package="cn.limbo">
  2. <!--不要將Service掃進來,否則aop無法使用-->
  3. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
  4. </context:component-scan>

這樣就可以成功解決ssh配置下不能使用aop的情況。看來掃描包的時候不能暴力直接全部掃描進來啊,真是成也掃描,敗也掃描,手動哭笑不得。

Spring--AOP 例子