Spring入门第二十课
返回通知,异常通知,环绕通知
看代码:
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; @Component
public 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 stub
int 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
int result = 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.ClassPathXmlApplicationContext@49c2faae: 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.ClassPathXmlApplicationContext@49c2faae: 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.ClassPathXmlApplicationContext@49c2faae: 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入门第二十课的更多相关文章
- Spring入门第二十九课
事务的隔离级别,回滚,只读,过期 当同一个应用程序或者不同应用程序中的多个事务在同一个数据集上并发执行时,可能会出现许多意外的问题. 并发事务所导致的问题可以分为下面三种类型: -脏读 -不可重复读 ...
- Spring入门第二十八课
事务的传播行为 当事务方法被另一个事务方法调用时,必须指定事务应该如何传播,例如:方法可能继续在现有事务中运行,也可能开启一个新的事务,并在自己的事务中运行. 事务的传播行为可以由传播属性指定.Spr ...
- Spring入门第二十六课
Spring中的事务管理 事务简介 事务管理是企业级应用程序开发中必不可少的技术,用来确保数据的完整性和一致性. 事务就是一系列的动作,他们被当做一个单独的工作单元,这些动作要么全部完成,要么全部不起 ...
- Spring入门第二十五课
使用具名参数 直接看代码: db.properties jdbc.user=root jdbc.password=logan123 jdbc.driverClass=com.mysql.jdbc.Dr ...
- Spring入门第二十四课
Spring对JDBC的支持 直接看代码: db.properties jdbc.user=root jdbc.password=logan123 jdbc.driverClass=com.mysql ...
- Spring入门第二十二课
重用切面表达式 我们有的时候在切面里面有多个函数,大部分函数的切入点都是一样的,所以我们可以声明切入点表达式,来重用. package logan.study.aop.impl; public int ...
- Spring入门第二十七课
声明式事务 直接上代码: db.properties jdbc.user=root jdbc.password=logan123 jdbc.driverClass=com.mysql.jdbc.Dri ...
- Spring入门第二十三课
我们看基于XML配置的方式配置AOP 看代码: package logan.study.aop.impl; public interface ArithmeticCalculator { int ad ...
- Spring入门第二十一课
切面优先级 先看代码: package logan.study.aop.impl; public interface ArithmeticCalculator { int add(int i, int ...
随机推荐
- 2017-2018-1 20179209《Linux内核原理与分析》第六周作业
一.分析system_call中断处理过程 实验 下载最新menu,并在test.c中增加mkdir与mkdir-asm函数原型 rm menu -rf git clone https://githu ...
- 【题解】P2602[JZOI2010]数字计数
[题解][P2602ZJOI2010]数字计数 乍看此题,感觉直接从数字的位上面动手,感觉应该很容易. 但是仔细看数据范围,发现如果不利用计数原理,肯定会超时,考虑数码出现的特征: \(A000\)到 ...
- 韩国版微信Kakao推出公链,能否用区块链实现全球扩张?
2018年是属于区块链的一年,国内外巨头们纷纷布局区块链产业,前不久韩国最大的移动社交平台Kakao集团正式启动了旗下的第一个公链Klaytn的测试网. 此次宣布只是一次试探性举措,旨在对外公布Kla ...
- FI 常用表
FI 常用表 GL部分:FAGLFLEXT(FMGLFLEXT) 总账汇总表 GLT0 旧总帐汇总表 SKA1 总账科目主记录 (科目表) ...
- Vue:实践学习笔记(5)——Vue-Cli脚手架的使用
Vue:实践学习笔记(5)——Vue-Cli脚手架的使用 快速开始 项目配置 可视化配置 vue ui 命令配置 vue init webpack vue-demo(项目名) 运行测试 进入vue-d ...
- 《C prime plus (第五版)》 ---第12章 存储类.链接和内存管理
12-1:存储类: 1.作用域: 代码块作用域,函数原型作用域和文件作用域. 2.链接:分为外部链接,内部链接和空链接.代码块作用域和函数原型作用域都是空连接,意味着是私有的.而文件作用域的变量可能是 ...
- Android Wifi简单的梳理【转】
本文转载自:http://blog.csdn.net/gabbzang/article/details/10005411 代表一个已经配置过的网络.包含网络ID(networkId).该网络ID代表的 ...
- hihocoder 微软编程之美2015 初赛 第二场(暴力+字典序+图论+思维算法)
题目1 : 扑克牌 时间限制:2000ms 单点时限:1000ms 内存限制:256MB 描述 一副不含王的扑克牌由52张牌组成,由红桃.黑桃.梅花.方块4组牌组成,每组13张不同的面值.现在给定52 ...
- linux shell发送邮件
我的系统环境: [root@NPS-JK ~]# cat /etc/issue Red Hat Enterprise Linux Server release 6.1 (Santiago) Kerne ...
- openfire调试环境
导入工程: File->New->project: 选择“Java project from existing ant buildfile” 再从菜单windows->show vi ...