场景:第三方调用校验是否有权限,就是常规的校验appId和secret,一个项目中有自己公司服务调用的也有第三方调用的
思路:在第三方调用的方法上添加一个自定义注解,在用aop拦截这个自定义注解
1.先自定义一个注解
@Documented
@Target({ElementType.METHOD})
@Inherited
@Retention(RetentionPolicy.RUNTIME )
public @interface OpenApi {/*** 开放平台的接口编码* @return*/String encode() default "";
}
2.定义aop拦截 有该注解的方法或类(注解应用范围具体看注解的Target配置,OpenApi是应用到方法)
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
@Slf4j
public class OpenApiAdvice {@Autowiredprivate IVerifyService iVerifyService;//调用的方法有该注解才会拦截@Pointcut("@annotation(com.cunw.cloud.dataworks.annotation.OpenApi)")private void annotationPointCut() {}//环绕 满足上面的拦截条件就会调用该方法@Around("annotationPointCut()")public Object annotationAround(ProceedingJoinPoint joinPoint) throws Throwable {//获取方法Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();//得到方法参数 这里是一个数组,因为我这里只有一个参数所以写了[0]Object args = joinPoint.getArgs()[0];// 获取该方法上的 OpenApi注解OpenApi aspectAnnotation = method.getAnnotation(OpenApi.class);//注解的方法(就是注解里定义的值)String encode = aspectAnnotation.encode();//写你的业务逻辑//校验appId,sign等参数iVerifyService.verify(args, openApiVO.getSecret());//正常往后执行return joinPoint.proceed();}}
3. 最后 想想 拦截器和aop有什么区别?