目的
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;
/**
* 定义一个切面
* @author admin
*/
@Aspect
@Component
public class AopAspect {
/**
* 定义切点Pointcut
*/
@Pointcut("execution(* com.xxx.xxx.*.controller..*.*(..))")
public void executionService() {
}
/**
* 环绕通知
* @param pjp
* @return
* @throws Throwable
*/
@Around("executionService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
Object o = pjp.proceed();
return o;
}
/**
* 后置通知 log打印
* @param joinPoint
*/
@After("executionService()")
public void afterMethod(JoinPoint joinPoint) {
}
/**
* 前置通知
* @param joinPoint
*/
@Before("executionService()")
public void beforeMethod(JoinPoint joinPoint) {
}
/**
* 返回通知
* @param joinpoint
* @param rvt
*/
@AfterReturning(pointcut = "executionService()", returning = "rvt")
public void afterReturningMethod(JoinPoint joinpoint, Object rvt) {
}
/**
* 异常通知
* @param joinPoint
*/
@AfterThrowing("executionService()")
public void afterThrowingMethod(JoinPoint joinPoint) {
}
}
2. 定义一个注解类
package com.ydfx.app.config.aop;
import java.lang.annotation.*;
/**
* @author admin
* @interface定义一个注解类
* @Target也是用来修饰注解的元注解 注解类型 ElementType.METHOD 可以生效在方法上 。 ElementType.TYPE 可以生效在类上
* Retention注解有一个属性value,是RetentionPolicy类型的,Enum RetentionPolicy是一个枚举类型,
* 这个枚举决定了Retention注解应该如何去保持,也可理解为Rentention 搭配 RententionPolicy使用。RetentionPolicy有3个值:CLASS RUNTIME SOURCE
* 用@Retention(RetentionPolicy.CLASS)修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,但不会被虚拟机读取在运行的时候;
* 用@Retention(RetentionPolicy.SOURCE )修饰的注解,表示注解的信息会被编译器抛弃,不会留在class文件中,注解的信息只会留在源文件中;
* 用@Retention(RetentionPolicy.RUNTIME )修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时,
* 所以他们可以用反射的方式读取。RetentionPolicy.RUNTIME 可以让你从JVM中读取Annotation注解的信息,以便在分析程序的时候使用.
* @Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中,是一个标记注解
*/
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthIdentity {
/**
* 接口类型 0 应聘者 1 招聘者
* @return
*/
int value() default 0;
}
3. 修改aop 的环绕通知
// 满足 excudePcService 和 authIdentity时会触发执行环绕通知
// @annotation 注解声明在类上无效
// @target 注解声明在方法上无效
@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) 注解