XML配置aop例項
阿新 • • 發佈:2020-07-15
直接上程式碼,首先我的結構目錄是:
1、新建一個MathAspect.java
public class MathAspect { //前置通知 public void logBefore(JoinPoint joinPoint) {//joinPoint 可以用來獲取方法引數以及方法名 Object[] args = joinPoint.getArgs(); System.out.println("" + joinPoint.getSignature().getName() + "除法執行前。。引數列表是:{" + Arrays.asList(args) + "}"); }//後置通知 public void logAfter(JoinPoint joinPoint) { System.out.println("" + joinPoint.getSignature().getName() + "除法執行結束。。"); } //返回通知 public void logReturn(JoinPoint joinPoint, int result) {//返回結果必須與xml檔案中returning同名,即returning="result" System.out.println("" + joinPoint.getSignature().getName() + "除法正常返回。。返回結果是:{" + result + "}"); }//異常通知 public void logException(JoinPoint joinPoint, Exception e) {//異常資訊必須與xml檔案中的throwing同名,即throwing="e" System.out.println("" + joinPoint.getSignature().getName() + "除法異常。。。異常是:{" + e + "}"); } }
2、新建需要增強的類:
public class MathCalculator { public int div(int i, int j) { System.out.println("MathCalculator...div..."); return i / j; } }
3、aop配置xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--定義切面類--> <bean class="com.aoptest.aop.MathAspect" name="aspect"/> <!--定義目標類--> <bean class="com.aoptest.aop.MathCalculator" id="calculator"/> <!--aop配置--> <aop:config> <!--定義切點,其中匹配的是com.aoptest.aop.MathCalculator類下面所有引數返回值任意的方法--> <aop:pointcut id="pointcut" expression="execution(* com.aoptest.aop.MathCalculator.*(..))"/> <aop:aspect ref="aspect"> <!--前置通知,method必須與切面類中的方法名相同(下同),並指定切點--> <aop:before method="logBefore" pointcut-ref="pointcut"/> <!--後置通知--> <aop:after method="logAfter" pointcut-ref="pointcut"/> <!--返回通知,返回值名與方法返回值名相同--> <aop:after-returning method="logReturn" pointcut-ref="pointcut" returning="result"/> <!--異常通知,異常名與方法返回的異常名相同--> <aop:after-throwing method="logException" pointcut-ref="pointcut" throwing="e"/> </aop:aspect> </aop:config> </beans>
4、測試類
public class MathTest { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MathCalculator calculator = (MathCalculator) context.getBean("calculator"); // calculator.div(10, 1); calculator.div(10, 0); } }
正常輸出結果:
div除法執行前。。引數列表是:{[10, 1]}
MathCalculator...div...
div除法執行結束。。
div除法正常返回。。返回結果是:{10}
異常輸出結果:
div除法執行前。。引數列表是:{[10, 0]} MathCalculator...div... Exception in thread "main" java.lang.ArithmeticException: / by zero div除法執行結束。。 at com.aoptest.aop.MathCalculator.div(MathCalculator.java:11) div除法異常。。。異常是:{java.lang.ArithmeticException: / by zero}