首先、需要一个自定义注解,如下:
1、
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorization {
}
2、
@Aspect
@Component
public class AuthorizationAspect {
@Resource
private CountVOMapper countVOMapper;
/**
* 定义切点
*/
@Pointcut("@annotation(com.bc.mcode.common.Authorization)")
public void executeService() {
}
/**
* 环绕织入
*/
@Around("executeService()&&@annotation(authorization)")
public Object proceed(ProceedingJoinPoint thisJoinPoint, Authorization authorization) {
Object proceed = null;
//获取到请求参数
Map<String, Object> fieldsName = getFieldsName(thisJoinPoint);
//这里是做业务逻辑的,如果是做访问次数的,需要有个表存次数,在这里获取并且做 i++,在更新数据库
try {
proceed = thisJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return proceed;
}
/**
* 获取接口上的参数列表,封装成map
* @param joinPoint
*/
private static Map<String, Object> getFieldsName(ProceedingJoinPoint joinPoint) {
// 参数值
Object[] args = joinPoint.getArgs();
ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String[] parameterNames = pnd.getParameterNames(method);
Map<String, Object> paramMap = new HashMap<>(32);
for (int i = 0; i < parameterNames.length; i++) {
paramMap.put(parameterNames[i], args[i]);
}
return paramMap;
}
}
3、最后一步是吧注解放在你需要监控的接口:
@RequestMapping("hhhh")
@ResponseBody
@Authorization
public GaxxVO queryGaxxVOById(Integer id,String types){
return gaxxVOService.queryByPrimaryKey(id);
}