1.JoinPoint
@AfterReturning("execution(* com..*.*Mapper.update*(..))|| execution(* com..*.*Mapper.insert*(..))"
+ " || execution(* com..*.*Mapper.add*(..))")
public int afterAddAndUpdate(JoinPoint joinPoint){
try {
String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName(); //1拦截方法所在类名
String methodName = joinPoint.getSignature().getName(); //2获取拦截到的方法名称
Object[] args = joinPoint.getArgs();//3获取参数值
String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();//参数名称
......
......
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
前面三个方法就是拿来就用,没什么问题,这个String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();需要注意的是,编译的时候需要用特殊的编译方式,才能获取到参数的名称,否则argNames=null,使用会报空指针异常;
在Java8之前,代码编译为class文件后,方法参数的类型固定,但是方法名称会丢失,方法名称会变成arg0、arg1….在Java8开始可以在class文件中保留参数名。
特殊编译的几种方式:
1.maven pom.xml 增加compilerArgs ,编译时使用maven compile
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
2.IDEA中设置
File–>Setting–>Java Compiler
3.eclipse中设置
window–>preferences->java->compiler下,选中Store information about method parameters
2.ProceedingJoinPoint
ProceedingJoinPoint是JoinPoint的子接口,用在@Around切面方法中,增加了proceed()方法
Object proceed() throws Throwable //执行目标方法
Object proceed(Object[] var1) throws Throwable //传入的新的参数去执行目标方法