创作背景
今天系统的学习了aop,写一个demo来练手强化和熟悉一下aop。
实现原理
通过自定义注解+aop切面编程实现。
代码实现
@Target({ElementType.METHOD}) //指定只能在方法上写
@Retention(RetentionPolicy.RUNTIME) //设定运行范围
public @interface CheckAuth {
String value();
}
@RestController
@RequestMapping("/book")
public class BookController {
@CheckAuth(value = "admin") //添加自定义注解并定义需要管理员权限
@GetMapping("/selectAllBooks")
public String select() {
return "查询成功";
}
}
@Data
public class User {
private int id;
private String name;
private String auth;
}
@Service
public class UserServiceImpl implements UserService {
@Override
public User getLoginUser() {
User user = new User();
user.setId(1);
user.setAuth("admin");
user.setName("xiaotao");
return user;
}
}
@Aspect
@Component
@Slf4j
public class BookAdvice {
@Resource
private UserService userService;
//环绕通知
@Around("@annotation(checkAuth)")
public Object around(ProceedingJoinPoint pjp, CheckAuth checkAuth) throws Throwable {
log.info("===============> log begin <=================");
//1.获取request对象
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
//2.获取请求的详情详细
String requestURI = request.getRequestURI();
String method = request.getMethod();
log.info("requestTime: {}", LocalDateTime.now());
log.info("requiredAuth: {}", checkAuth.value());
log.info("requestURI: {}", requestURI);
log.info("method: {}", method);
//打印所有请求头
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {//通过Enumeration类中的hasMoreElements()判断是否还有参数名
String parameterName = (String) headerNames.nextElement(); //获取当前参数名
//再通过request.getParameter("")的方法来获取对应参数名的值
log.info("Request Header: {}: {}", parameterName, request.getHeader(parameterName));
}
//打印请请求体
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String parameterName = (String) e.nextElement();
log.info("Request parameters: {}: {}", parameterName, request.getParameter(parameterName));
}
//3.判断权限是否符合
User loginUser = userService.getLoginUser();
if (loginUser != null) {
String auth = checkAuth.value();
if (loginUser.getAuth().equals(auth)) {
log.info("权限校验完成,权限符合");
log.info("===============> log end <=================");
return pjp.proceed();
}
}
log.error("权限不足");
log.info("===============> log end <=================");
//4.不符合条件的均为权限不足
throw new RuntimeException("权限不足");
}
}