JoinPoint和ProceedingJoinPoint对象
-
JoinPoint对象封装了SpringAop中切面方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该方法信息的JoinPoint对象. -
ProceedingJoinPoint对象是JoinPoint的子接口,该对象只用在@Around的切面方法中
@Aspect
@Component
public class aopAspect {
/**
* 定义一个切入点表达式,用来确定哪些类需要代理
* execution(* aopdemo.*.*(..))代表aopdemo包下所有类的所有方法都会被代理
*/
@Pointcut("execution(* aopdemo.*.*(..))")
public void declareJoinPointerExpression() {}
/**
* 前置方法,在目标方法执行前执行
* @param joinPoint 封装了代理方法信息的对象,若用不到则可以忽略不写
*/
@Before("declareJoinPointerExpression()")
public void beforeMethod(JoinPoint joinPoint){
System.out.println("目标方法名为:" + joinPoint.getSignature().getName());
System.out.println("目标方法所属类的简单类名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("目标方法所属类的类名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
//获取传入目标方法的参数
Object[] args = joinPoint.getArgs();
for (int i = 0; i
切点表达式
- 在Spring AOP中,连接点始终代表方法的执行。切入点是与连接点匹配的,切入点表达语言是以编程方式描述切入点的方式。
- 切入点(Poincut)是定义了在“什么地方”进行切入,哪些连接点会得到通知。显然,切点一定是连接点
- 切点是通过
@Pointcut注解和切点表达式定义的。@Pointcut注解可以在一个切面内定义可重用的切点。
execute表达式
*代表匹配任意修饰符及任意返回值,参数列表中..匹配任意数量的参数
可以使用&&、||、!、三种运算符来组合切点表达式,表示与或非的关系
- 1.拦截任意公共方法
execution(public * *(..)) - 2.拦截以set开头的任意方法
execution(* set*(..)) - 3.拦截类或者接口中的方法
拦截AccountService(类、接口)中定义的所有方法 execution(* com.xyz.service.AccountService.*(..))
4.拦截包中定义的方法,不包含子包中的方法
拦截com.xyz.service包中所有类中任意方法,**不包含**子包中的类 execution(* com.xyz.service.*.*(..))
5.拦截包或者子包中定义的方法
拦截com.xyz.service包或者子包中定义的所有方法 execution(* com.xyz.service..*.*(..))
通知分类
@Before
- 前置通知: 在方法执行之前执行
- 前置通知使用
@Before注解 将切入点表达式值作为注解的值

@After
- 后置通知, 在方法执行之后执行
- 后置通知使用
@After注解 ,在后置通知中,不能访问目标方法执行的结果

@AfterRunning
- 返回通知, 在方法返回结果之后执行
- 返回通知使用
@AfterRunning注解


@AfterThrowing
- 异常通知, 在方法抛出异常之后执行
- 异常通知使用
@AfterThrowing注解

@Around
- 环绕通知, 围绕着方法执行
- 环绕通知使用
@Around注解

package com.jason.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.springframework.stereotype.Component;
//把这个类声明为一个切面
//1.需要将该类放入到IOC 容器中
@Component
//2.再声明为一个切面
@Aspect
public class LoggingAspect {
//声明该方法是一个前置通知:在目标方法开始之前执行 哪些类,哪些方法
//作用:@before 当调用目标方法,而目标方法与注解声明的方法相匹配的时候,aop框架会自动的为那个方法所在的类生成一个代理对象,在目标方法执行之前,执行注解的方法
//支持通配符
//@Before("execution(public int com.jason.spring.aop.impl.ArithmeticCaculatorImpl.*(int, int))")
@Before("execution(* com.jason.spring.aop.impl.*.*(int, int))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。
