第一种:使用切入点
@Slf4j
@Component
@Aspect
public class DemoAop {
@Autowired
private ElasticSearchService<DemoEntity> esService;
@Pointcut("execution(* com.xxx.xxx.mapper.xxmapper.DemoMapper.batchDemo(..))")
public void pointCut() {
//
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
log.info("es保存设备当前位置信息:{}", args);
try {
List<Demo> entityList = Lists.newArrayList();
// 索引为0的位置保存所有参数信息
if (args[0].getClass() == ArrayList.class) {
List<Demo> demoList= (ArrayList)args[0];
for (Demo demo : demoList) {
entityList.add(demo);
}
}
esService.save(entityList);
} catch (Exception e) {
log.error("设备当前位置信息保存es失败:{}", e);
} finally {
return pjp.proceed(args);
}
}
}
第二种:使用注解
@Component
@Aspect
public class ParameterCheckAopHandler {
// 对有ParameterCheck注解的方法进行拦截
@Around("@annotation(com.xxx.xx.xx.xx.ParameterCheck)")
@Order(2)
public Object parameterCheck(ProceedingJoinPoint joinPoint) throws Throwable {
Object target = joinPoint.getTarget();
Class<?> clazz = target.getClass();// 目标类
String methodName = joinPoint.getSignature().getName();// 方法名
Object[] args = joinPoint.getArgs();// 参数
// 通过反射获取对象注解的方法
Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
// 获取该方法在参数上的注解,每个参数可以有多个注解,得到的是一个二维数组
Annotation[][] parameterAnnotaions = method.getParameterAnnotations();
if (parameterAnnotaions == null || parameterAnnotaions.length == 0) {
return joinPoint.proceed(args);
}
for (int i = 0; i < parameterAnnotaions.length; i++) {
Annotation[] oneParameterAnnotaions = parameterAnnotaions[i];
if (oneParameterAnnotaions == null || oneParameterAnnotaions.length == 0) {
continue;
}
for (int j = 0; j < oneParameterAnnotaions.length; j++) {
// 1.正则校验
if (oneParameterAnnotaions[j].annotationType() == Pattern.class) {
Pattern pattern = (Pattern)oneParameterAnnotaions[j];
if (args[i] != null) {
String regexp = pattern.regexp();
java.util.regex.Pattern patt = java.util.regex.Pattern.compile(regexp);
boolean matched = patt.matcher(args[i].toString()).matches();
if (!matched) {
throw new Exception(args[i] + "格式不正确");
}
}
}
// 2.针对user注解校验
if (oneParameterAnnotaions[j].annotationType() == InjectUserInfo.class) {
UserInfo userInfo = (UserInfo)args[i];
if (null == userInfo || null == userInfo.getUser()) {
throw new Exception("无效用户信息");
}
}
}
}
return joinPoint.proceed(args);
}
}