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

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. 《从零开始学Swift》学习笔记(Day 37)——默认构造函数

    原创文章,欢迎转载.转载请注明:关东升的博客 结构体和类的实例在构造过程中会调用一种特殊的init方法,称为构造函数.构造函数没有返回值,可以重载.在多个构造函数重载的情况下,运行环境可以根据它的外部 ...

  2. FlaskWeb开发

    Flask基本使用 上下文 程序上下文 current_app g 请求上下文 request session https://blog.csdn.net/wsxqaz/article/details ...

  3. Django中间件,信号,缓存

    中间件 django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法. 在django项 ...

  4. Android系统移植与调试之------->如何修改Android系统默认显示【开发者选项】并默认打开【USB调试】和【未知来源】开关

    今天有个用户对[设置]有个特殊的要求,即: 1.开机的时候默认显示[开发者选项]并打开[USB调试]开关    ([Developer options]-->[USB debugging]) 2 ...

  5. java基础:父类与子类之间变量和方法的调用

    1)父类构造函数 java中当调用某个类的构造方法的时候,系统总会调用父类的非静态初始化块进行初始化,这个调用是隐式的,而且父类的静态初始化代码 块总是会被执行,接着调用父类的一个或者多个构造器执行初 ...

  6. 图的遍历:DFS和BFS

    图的遍历一般由两者方式:深度优先搜索(DFS),广度优先搜索(BFS),深度优先就是先访问完最深层次的数据元素,而BFS其实就是层次遍历,每一层每一层的遍历. 1.深度优先搜索(DFS) 我一贯习惯有 ...

  7. 启动 nodemanger 报错javax.security.sasl.SaslException: GSS initiate failed

    最近启动 Hadoop, nodemanger 老挂,报kerberos 验证错误,各种查找原因,时间也同步,kint 也能登录到kerberos,一直找不到原因,最后发现是网关和远端的时间同步,但是 ...

  8. windows server2003/2008中权限账户

    在windows server 2003与windows server 2008 R2中,查看文件夹权限时,尤其是用cacls命令查看时,经常会见nt authority system这样的用户信息. ...

  9. 转载:http://blog.csdn.net/foruok/article/details/53500801

    凭兴趣求职80%会失败,为什么 标签: 求职跳槽找工作兴趣技术 2016-12-07 06:51 43316人阅读 评论(69) 收藏 举报 本文章已收录于:   分类: 随笔(144) 作者同类文章 ...

  10. java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]

    Links: 1.Getting availableProcessors is already set to [1], rejecting [1] IllegalStateException exce ...