实现两个整数的加减乘除、在执行每个方法之前打印日志。

ArithmeticCalculator.java:

package spring.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); }

ArithmeticCalculatorImpl.java:

package spring.aop.impl;

import org.springframework.stereotype.Component;

@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator { public int add(int i, int j) {
int result = i+j;
return result;
} public int sub(int i, int j) {
int result = i-j;
return result;
} public int mul(int i, int j) {
int result = i*j;
return result;
} public int div(int i, int j) {
int result = i/j;
return result;
} }

LoggingAspect.java:

package spring.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.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Order(1)//如果有多个切面,可以使用@Order来指定切面的优先级,值越小优先级越高
@Aspect
@Component
public class LoggingAspect { /**
* 定义一个方法,定义切入点表达式,一般地,这个方法中不添加其它代码
* 怎么使用?
* 1.如果在本类,如@Before("declareJoinPointExpression()"),直接用方法名来引用
* 2.在另一个包的类或其他类,如@Before("包名.类名.declareJoinPointExpression()")
*/
@Pointcut("execution(public int spring.aop.impl.ArithmeticCalculator.*(..))")
public void declareJoinPointExpression(){} /**
* 在spring.aop.impl.ArithmeticCalculator接口的每一个实现类的每一个开始之前执行一段代码
*/
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
List<Object> args=Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" begins "+args);
} /**
* 在方法之后执行(不论是否抛出异常)
* @param joinPoint
*/
@After("execution(public int spring.aop.impl.ArithmeticCalculator.*(..))")
public void afterMethod(JoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
List<Object> args=Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" ends ");
} /**
* 在方法正常执行后的通知
* 返回通知是可以访问到方法的返回值的
* @param joinPoint
*/
@AfterReturning(value="execution(public int spring.aop.impl.ArithmeticCalculator.*(..))",
returning="result")
public void afterReturnMethod(JoinPoint joinPoint,Object result){
String methodName=joinPoint.getSignature().getName();
System.out.println("The method "+methodName+" ends with afterReturning "+ result);
} /**
* 在目标方法出现异常时会执行的代码
* 可以访问出现的异常信息,可以指定出现指定异常时执行
* 方法参数Exception改为其它异常可以指定出现指定异常时执行
* @param joinPoint
* @param ex
*/
@AfterThrowing(value="execution(public int spring.aop.impl.ArithmeticCalculator.*(..))",
throwing="ex")
public void afterThrowing(JoinPoint joinPoint,Exception ex){
String methodName=joinPoint.getSignature().getName();
System.out.println("The method "+methodName+" occurs exection: "+ ex);
} /**
* 环绕通知
* 需要携带ProceedingJoinPoint类型的参数
* 类似于动态代理的全过程:ProceedingJoinPoint类型参数可以决定是否执行目标方法
* 环绕通知必须有返回值,返回值就是目标方法的返回值
* @param joinPoint
*/
/*
@Around("execution(public int spring.aop.impl.ArithmeticCalculator.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){ Object result=null;
String methodName=joinPoint.getSignature().getName();
try {
//前置通知
System.out.println("---->The method "+methodName+" begins with" +Arrays.asList(joinPoint.getArgs()));
//执行目标方法
result=joinPoint.proceed();
//返回通知
System.out.println("---->"+result);
} catch (Throwable e) {
e.printStackTrace();
//异常通知
System.out.println("---->"+e);
} //后置通知
System.out.println("---->The method "+methodName+ "ends");
return result;
}
*/
}

ApplicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.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="spring.aop.impl"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

测试:

package spring.aop.impl.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import spring.aop.impl.ArithmeticCalculator; public class Main { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
ArithmeticCalculator arithmeticCalculator=(ArithmeticCalculator) ctx.getBean("arithmeticCalculator"); int result=arithmeticCalculator.add(10, 20);
System.out.println("result:"+result); result=arithmeticCalculator.div(10, 0);
System.out.println("result:"+result);
} }

输出:

The method add begins [10, 20]
The method add ends
The method add ends with afterReturning 30
result:30
The method div begins [10, 0]
The method div ends
The method div occurs exection: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.ArithmeticException: / by zero
at spring.aop.impl.ArithmeticCalculatorImpl.div(ArithmeticCalculatorImpl.java:24)
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:497)
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.$Proxy12.div(Unknown Source)
at spring.aop.impl.test.Main.main(Main.java:18)

Spring初学之annotation实现AOP前置通知、后置通知、返回通知、异常通知。的更多相关文章

  1. [转载] Spring框架——AOP前置、后置、环绕、异常通知

    通知类型: 步骤: 1. 定义接口 2. 编写对象(被代理对象=目标对象) 3. 编写通知(前置通知目标方法调用前调用) 4. 在beans.xml文件配置 4.1 配置 被代理对象=目标对象 4.2 ...

  2. Spring初学之annotation实现AOP前置通知和后置通知

    实现两个整数的加减乘除,并在每个计算前后打印出日志. ArithmeticCalculator.java: package spring.aop.impl; public interface Arit ...

  3. Spring(十八):Spring AOP(二):通知(前置、后置、返回、异常、环绕)

    AspectJ支持5种类型的通知注解: @Before:前置通知,在方法执行之前执行: @After:后置通知,在方法执行之后执行: @AfterRunning:返回通知,在方法返回结果之后执行(因此 ...

  4. Spring初学之xml实现AOP前置通知、后置通知、返回通知、异常通知等

    实现两个整数的加减乘除,在每个方法执行前后打印日志. ArithmeticCalculator.java: package spring.aop.impl.xml; public interface ...

  5. spring的几个通知(前置、后置、环绕、异常、最终)

    1.没有异常的 2.有异常的 1.被代理类接口Person.java package com.xiaostudy; /** * @desc 被代理类接口 * * @author xiaostudy * ...

  6. C++之运算符重载(前置++和后置++)

    今天在阅读<google c++ 编程风格>的文档的时候,5.10. 前置自增和自减:有一句话引起了我的注意: 对于迭代器和其他模板对象使用前缀形式 (++i) 的自增, 自减运算符.,理 ...

  7. spring的AspectJ基于XML和注解(前置、后置、环绕、抛出异常、最终通知)

    1.概念 (1)AspectJ是一个基于Java语言的AOP框架 (2)Spring2.0以后新增了对AspectJ切入点表达式的支持 (3)AspectJ是AspectJ1.5的新增功能,通过JDK ...

  8. PHP通过__call实现简单的AOP(主事务后的其他操作)比如前置通知,后置通知

    /** * person class */ class Person { /** * person class -> function say */ public static function ...

  9. 20_AOP_Advice增强1(前置、后置、环绕)

    [增强的类型] 1.前置增强:org.springframework.aop.BeforeAdvice. 由于Spring只支持方法级别的增强,所以MethodBeforeAdvice是目前可用的前置 ...

随机推荐

  1. 第三章 T-SQL 编程

    3.1 使用变量 变量是可以存储数据值的对象.可以使用局部变量向SQL语句传递数据.在T-SQL中执行一批SQL语句时,可以声明许多变量以便临时使用.声明变量以后,可以在批处理中用一条T-SQL语句设 ...

  2. Intellij IDEA工具的常用快捷键

    掌握如下常用快捷键可以使自己的开发效率提供十倍. ctrl + B : 转到类或者方法的定义 ctrl + Alt + B:弹出接口/虚类的实现类/子类 ctrl + Alt + 左箭头/右箭头 : ...

  3. WCF基础之传输

    WCF中使用的主要传输的方式有HTTP,TCP和命名管道. 绑定包括可选的协议绑定元素(如安全),必需的编码绑定元素和必须的传输协定绑定元素三个部分,而由传输方式则是由传输绑定元素来决定的. HTTP ...

  4. 通知url必须为直接可访问的url,不能携带参数 异步接收微信支付结果通知的回调地址 不能携带参数。 回调地址后是否可以加自定义参数 同步回调地址 异步回调地址 return_url和notify_url的区别

    [微信支付]微信小程序支付开发者文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7 通知url必须为直接可访问的 ...

  5. REST --- Representational State Transfer --- 表现层状态转化

    引用:阮一峰的网络日志 如果一个架构符合REST原则,就称它为RESTful架构. 要理解RESTful架构,最好的方法就是去理解Representational State Transfer这个词组 ...

  6. jquerymobile模板

    <!DOCTYPE html> <html> <head> <title>Page Title</title> <meta name= ...

  7. Java基础—String总结

    特点 String不属于8种基本数据类型,String是一个对象. 因为对象的默认值是null,所以String的默认值也是null:但它又是一种特殊的对象,有其它对象没有的一些特性. String实 ...

  8. Eclipse中执行maven命令(转载)

    转载自:http://blog.csdn.net/u011939453/article/details/43017865 1.如下图,右击需要执行maven命令的工程,选择"Debug As ...

  9. 算法题 18 像素翻转 牛客网 CC150

    算法题 18 像素翻转 牛客网 CC150_P114 题目描述 有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,在不占用额外内存空间的情况下(即不使用缓存矩阵),将图像顺时 ...

  10. win7下配置JAVA环境变量

    首先安装JDK,jdk-6u10-rc2-bin-b32-windows-i586-p-12_sep_2008 找到安装目录,并记下,D:\Program Files (x86)\Java\jdk1. ...