文章内容
1、maven依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、自定义注解
package com.ntan520.core.permission;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PermissionAnnotation {
String uuid() default "";
}
3、启动类配置
package com.ntan520.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author Nick Tan
*/@SpringBootApplication
@ComponentScan(basePackages = { "com.ntan520" })
@EnableAspectJAutoProxy
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
4、AOP切面类
package com.ntan520.core.permission;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.ntan520.core.exception.ErrorException;
import com.ntan520.core.result.ResultEnum;
@Aspect
@Component
public class PermissionAspect {
@Pointcut("@annotation(com.ntan520.core.permission.PermissionAnnotation)")
public void annotationPointCut() {
}
@Before("annotationPointCut()")
public void before(JoinPoint joinPoint) {
MethodSignature sign = (MethodSignature) joinPoint.getSignature();
Method method = sign.getMethod();
System.out.println("接受方法:" + method.getName() + " 前置日志");
if (method.isAnnotationPresent(PermissionAnnotation.class)) {
PermissionAnnotation annotation = method.getAnnotation(PermissionAnnotation.class);
System.out.println(annotation.uuid());
//TODO 权限校验
}
throw new ErrorException(ResultEnum.PARAM_ERROR.getCode(), ResultEnum.PARAM_ERROR.getMessage());
}
}
5、注解使用
package com.ntan520.test.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ntan520.core.permission.PermissionAnnotation;
import com.ntan520.core.result.Result;
import com.ntan520.core.result.ResultEnum;
/**
* @author Nick Tan
*/@RestController
public class TestController {
@GetMapping("/test")
@PermissionAnnotation(uuid = "132312")
public Result test() {
System.out.println("=======================");
return Result.instance(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
}
}