Spring入門第二十課
阿新 • • 發佈:2017-05-28
ini pointer lns 後置 獲取 結果 ssp version text
返回通知,異常通知,環繞通知
看代碼:
package logan.study.aop.impl; public interface ArithmeticCalculator { int add(int i, int j); int sub(int i, int j); int mul(int i, int j); int div(int i, int j); }
package logan.study.aop.impl; import org.springframework.stereotype.Component; @Componentpublic class ArithmeticCalculatorImpl implements ArithmeticCalculator { @Override public int add(int i, int j) { // TODO Auto-generated method stub int result = i + j; return result; } @Override public int sub(int i, int j) { // TODO Auto-generated method stubint result = i - j; return result; } @Override public int mul(int i, int j) { // TODO Auto-generated method stub int result = i * j; return result; } @Override public int div(int i, int j) { // TODO Auto-generated method stub intresult = i / j; return result; } }
package logan.study.aop.impl; import java.util.Arrays; import java.util.List; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; //把這個類聲明為一個切面:需要把該類放入到IOC容器中,在聲明為一個切面 @Aspect @Component public class LoggingAspect { //聲明該方法時一個前置通知:在目標方法開始之前執行 @Before("execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))") public void beforeMethod(JoinPoint joinPoint){ String methodName = joinPoint.getSignature().getName(); List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println("The method "+ methodName +" begins with "+args); } //後置通知,在目標方法執行之後執行(無論該方法是否出現異常) //在後置通知中,還不能訪問目標方法執行的結果,執行結果在返回通知中可以訪問 @After("execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))") public void afterMethod(JoinPoint joinPoint){ String methodName = joinPoint.getSignature().getName(); List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println("The method "+ methodName +" ends with "+args); } //返回通知,在方法正常結束時執行的代碼 //返回通知是可以訪問返回值的 @AfterReturning(value="execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))", returning="result") public void afterReturningMethod(JoinPoint joinPoint,Object result){ String methodName = joinPoint.getSignature().getName(); System.out.println("The method "+ methodName +" ends with "+result); } //異常通知,在方法拋出異常時調用 @AfterThrowing(value="execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))", throwing="ex") public void afterThrowingMethod(JoinPoint joinPoint,Exception ex){ String methodName = joinPoint.getSignature().getName(); System.out.println("The method "+ methodName +" occus with "+ex); } }
<?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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <context:component-scan base-package="logan.study.aop.impl"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
package logan.study.aop.impl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub //1.創建Spring的IOC容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.從IOC容器裏面獲取bean實例 ArithmeticCalculator arithmeticCalculator = ctx.getBean(ArithmeticCalculator.class); //使用Bean int result = arithmeticCalculator.add(3, 6); System.out.println(result); result = arithmeticCalculator.div(3, 0); System.out.println(result); } }
執行結果:
五月 28, 2017 6:23:42 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContex[email protected]: startup date [Sun May 28 06:23:42 CST 2017]; root of context hierarchy 五月 28, 2017 6:23:42 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [applicationContext.xml] The method add begins with [3, 6] The method add ends with [3, 6] The method add ends with 9 9 The method div begins with [3, 0] The method div ends with [3, 0] The method div occus with java.lang.ArithmeticException: / by zero Exception in thread "main" java.lang.ArithmeticException: / by zero at logan.study.aop.impl.ArithmeticCalculatorImpl.div(ArithmeticCalculatorImpl.java:32) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:47) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy10.div(Unknown Source) at logan.study.aop.impl.Main.main(Main.java:18)
在這裏稍微改改代碼:我們把異常改成空指針異常
package logan.study.aop.impl; import java.util.Arrays; import java.util.List; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; //把這個類聲明為一個切面:需要把該類放入到IOC容器中,在聲明為一個切面 @Aspect @Component public class LoggingAspect { //聲明該方法時一個前置通知:在目標方法開始之前執行 @Before("execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))") public void beforeMethod(JoinPoint joinPoint){ String methodName = joinPoint.getSignature().getName(); List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println("The method "+ methodName +" begins with "+args); } //後置通知,在目標方法執行之後執行(無論該方法是否出現異常) //在後置通知中,還不能訪問目標方法執行的結果,執行結果在返回通知中可以訪問 @After("execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))") public void afterMethod(JoinPoint joinPoint){ String methodName = joinPoint.getSignature().getName(); List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println("The method "+ methodName +" ends with "+args); } //返回通知,在方法正常結束時執行的代碼 //返回通知是可以訪問返回值的 @AfterReturning(value="execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))", returning="result") public void afterReturningMethod(JoinPoint joinPoint,Object result){ String methodName = joinPoint.getSignature().getName(); System.out.println("The method "+ methodName +" ends with "+result); } //異常通知,在方法拋出異常時調用 @AfterThrowing(value="execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))", throwing="ex") public void afterThrowingMethod(JoinPoint joinPoint,NullPointerException ex){ String methodName = joinPoint.getSignature().getName(); System.out.println("The method "+ methodName +" occus with "+ex); } }
執行結果:
五月 28, 2017 6:28:32 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContex[email protected]: startup date [Sun May 28 06:28:32 CST 2017]; root of context hierarchy 五月 28, 2017 6:28:32 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [applicationContext.xml] The method add begins with [3, 6] The method add ends with [3, 6] The method add ends with 9 9 The method div begins with [3, 0] The method div ends with [3, 0] Exception in thread "main" java.lang.ArithmeticException: / by zero at logan.study.aop.impl.ArithmeticCalculatorImpl.div(ArithmeticCalculatorImpl.java:32) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:47) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy10.div(Unknown Source) at logan.study.aop.impl.Main.main(Main.java:18)
可以看到異常通知沒有執行。只有當發生空指針異常時才會執行。
下面看環繞通知:
package logan.study.aop.impl; import java.util.Arrays; import java.util.List; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; //把這個類聲明為一個切面:需要把該類放入到IOC容器中,在聲明為一個切面 @Aspect @Component public class LoggingAspect { /** * 環繞通知需要攜帶ProceedingJoinPoint類型的參數 * 環繞通知類似於動態代理的全過程:ProceedingJoinPoint類型的參數可以決定是否執行目標方法 * 且環繞通知必須有返回值,返回值即為目標方法的返回值 */ @Around("execution(public int logan.study.aop.impl.ArithmeticCalculator.*(int, int))") public Object aroundMethod(ProceedingJoinPoint pjd){ Object result = null; String methodName = pjd.getSignature().getName(); //執行目標方法 try{ //前置通知 System.out.println("The method" + methodName + " begins with " + Arrays.asList(pjd.getArgs())); result = pjd.proceed(); //返回通知 System.out.println("The method" + methodName + " ends with " + result); }catch(Throwable e){ //異常通知 System.out.println("The method occurs exception:" + e); } //後置通知 System.out.println("The method " + methodName + "ends"); return result; } }
package logan.study.aop.impl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub //1.創建Spring的IOC容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.從IOC容器裏面獲取bean實例 ArithmeticCalculator arithmeticCalculator = ctx.getBean(ArithmeticCalculator.class); //使用Bean int result = arithmeticCalculator.add(3, 6); System.out.println(result); result = arithmeticCalculator.div(3, 0); System.out.println(result); } }
返回結果:
五月 28, 2017 6:51:09 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContex[email protected]: startup date [Sun May 28 06:51:09 CST 2017]; root of context hierarchy 五月 28, 2017 6:51:09 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [applicationContext.xml] The methodadd begins with [3, 6] The methodadd ends with 9 The method addends 9 The methoddiv begins with [3, 0] The method occurs exception:java.lang.ArithmeticException: / by zero The method divends Exception in thread "main" org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract int logan.study.aop.impl.ArithmeticCalculator.div(int,int) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:227) at com.sun.proxy.$Proxy7.div(Unknown Source) at logan.study.aop.impl.Main.main(Main.java:18)
環繞通知一般來說不常用。
Spring入門第二十課