需要导入的包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
配置文件
<!--配置自动扫描的包-->
<context:component-scan base-package="com.li.aop.impl"></context:component-scan>
<!--使AspjectJ 注解起作用,自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
LoggingAsgectj 类是前置通知类
package com.li.aop.impl; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; //把这个类声明为一个切面:需要把该类放入到IOC容器中 @Aspect @Component public class LoggingAsgectj { //声明该方法是一个前置通知,在目标方法开始之前执行 @Before("execution(public int com.li.aop.impl.AtithmeticCalculatorImpl.add(int,int))") public void beforeMethod(){ System.out.println("before"); } }
在些方法前执行
package com.li.aop.impl; import org.springframework.stereotype.Component; @Component public class AtithmeticCalculatorImpl implements AtithmeticCalculator { //此方法前执行 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; } }
@After 后置通知
@Order 优先级
@Pointcut 重用切入点表达式
package com.li.aop.after; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Aspect @Component public class AfterMethod { //定义声名切入点表达式的方法 @Pointcut("execution(public int com.li.aop.after.AtithmeticCalculatorImpl.*(int,int))") public void decelareJoinPointExecution(){ } //后置通知 @After("decelareJoinPointExecution()") public void afterMethod(JoinPoint joinPoint){ System.out.println("after..."); } //后置返回通知 @AfterReturning("decelareJoinPointExecution()") public void afterMethodReturn(JoinPoint joinPoint){ System.out.println("afterReturn..."); } //后置异常通知 @AfterThrowing(value = "decelareJoinPointExecution()",throwing = "ex") public void afterMethodThrowing(JoinPoint joinPoint, Exception ex){ System.out.println("afterThrowing..."); } //环绕通知 @Around("decelareJoinPointExecution()") public int aroundMethodReturn(ProceedingJoinPoint proceedingJoinPoint){ System.out.println("aroundReturn..."); return 100; } }