//1.首先开启自动代理
@Configuration
@EnableAspectJAutoProxy
public class TokenEndPointAspectConfiguration {
@Bean
public TokenEndPointAspec tokenEndPointAspec() {
return new TokenEndPointAspec();
}
}
//2.定义切面
//在配置类TokenEndPointAspectConfiguration中已经定义bean,这里可以不用使用注解@Component
@Aspect public class TokenEndPointAspec {
}
/**
*3。定义切点
*com.company.controller.*.*(..))调用controller包下的任意类的任意方法时均会调用此方法
*/
@Pointcut("execution(* com.company.controller.*.*(..)))")
public void loggingPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the
// advices.
}
//4.定义通知
@Around("loggingPointcut()")
public Object run2(ProceedingJoinPoint joinPoint) throws Throwable {
//获取方法参数值数组
Object[] args = joinPoint.getArgs();
//得到其方法签名
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取方法参数类型数组
Class[] paramTypeArray = methodSignature.getParameterTypes();
if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {
//如果方法的参数列表最后一个参数是entityManager类型,则给其赋值
args[args.length - 1] = entityManager;
}
logger.info("请求参数为{}",args);
//动态修改其参数
//注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)
Object result = joinPoint.proceed(args);
logger.info("响应结果为{}",result);
//如果这里不返回result,则目标对象实际返回值会被置为null
return result;
}