目的
1. 日志打印
2. 接口权限
实现方式 aop + 自定义注解
1. 首先是aop
package com.ydfx.app.config.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AopAspect {
@Pointcut("execution(* com.xxx.xxx.*.controller..*.*(..))")
public void executionService() {
}
@Around("executionService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
Object o = pjp.proceed();
return o;
}
@After("executionService()")
public void afterMethod(JoinPoint joinPoint) {
}
@Before("executionService()")
public void beforeMethod(JoinPoint joinPoint) {
}
@AfterReturning(pointcut = "executionService()", returning = "rvt")
public void afterReturningMethod(JoinPoint joinpoint, Object rvt) {
}
@AfterThrowing("executionService()")
public void afterThrowingMethod(JoinPoint joinPoint) {
}
}
2. 定义一个注解类
package com.ydfx.app.config.aop;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthIdentity {
int value() default 0;
}
3. 修改aop 的环绕通知
@Around("excudePcService() && @annotation(authIdentity)")
public Object doAround(ProceedingJoinPoint pjp, AuthIdentity authIdentity) throws Throwable {
User user = userService.getUser();
if (user == null) {
return AppResult.errorReturn(403, "已退出登录");
}
Integer value = authIdentity.value();
if (value.equals(user.getUserType())) {
Object o = pjp.proceed();
return o;
} else {
return AppResult.errorReturn(403, "身份不匹配,权限不足");
}
}
4. 方法上或类上追加@AuthIdentity(1) 或 @AuthIdentity(2) 注解