首先集成aspectJ 到项目中
集成完成后:
自定义权限注解
import java.lang.annotation.*;
@documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckPermission {
String[] value();
}
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Aspect
@Component
public class ControllerAOP {
//定义切入点
@Pointcut("execution(public * space.*.controller..*.*(..))")
public void controllerAop() {
}
@Around("controllerAop()")
public Object Around(ProceedingJoinPoint joinPoint) throws Throwable {
//从session中获取之前存入的权限组
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpSession session = requestAttributes.getRequest().getSession();
List permissionList = (List) session.getAttribute("permissionList");
//获取拦截的方法上使用自定义注解标注需要的权限
CheckPermission annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(CheckPermission.class);
if(annotation == null){//没加权限注解,直接放行
return joinPoint.proceed();
}
//如果session中权限组含有该权限,放行
if(permissionList.contains(annotation.value()))
return joinPoint.proceed();
else{
return new ErrorResult<>("你没有权限访问~","");
}
}
}
测试
@PostMapping("test")
@CheckPermission("sys:test")//表明该方法需要sys:test权限
public Object update(Test test){
return testService.update(test);
}
当访问 controller中test 方法的时候,aop会拦截请求,判断session中权限组有没有该权限。没有则拦截



