<!-- aop依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PermissionLimit {
String value() default "";
boolean limit() default true;
boolean adminuser() default false;
}
import com.example.study.annotation.PermissionLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.example.study.annotation.PermissionLimit)")
public void pointcut() { }
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) {
Object result = null;
try {
result = point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
PermissionLimit logAnnotation = method.getAnnotation(PermissionLimit.class);
if (logAnnotation != null) {
System.out.println(logAnnotation.value());
}
return result;
}
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.study.annotation.PermissionLimit;
@RestController
public class UserController {
@RequestMapping("test")
public String test() {
try {
System.out.println("123");
} catch (Exception e) {
logger.info("邮件发送失败:", e);
}
return "over";
}
@PermissionLimit("邮件发送456")
@RequestMapping("test1")
public String test1() {
try {
System.out.println("456");
} catch (Exception e) {
logger.info("邮件发送失败:", e);
}
return "over";
}
}