应用场景: 判断接口是否缓存,业务添加操作日志等
1.添加核心依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
2.添加注解
import java.lang.annotation.*;
/**
* 自定义权限认证注解
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckPreAuthorize {
}
3.配置切面类,@Pointcut指定切点,pointcut同理
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 权限管理Aop切面
*/
@Aspect
@Component
public class PreAuthorizeAspect {
/**
* 添加切入点
*/
@Pointcut("@annotation(vip.hblg.iot.annotation.CheckPreAuthorize)")
public void checkPreAuthorize() {
}
/**
* 之前操作
*/
@Before("checkPreAuthorize()")
public void check() {
System.out.println("经过之前验证");
}
/**
* 之后操作
*/
@After("checkPreAuthorize()")
public void check2() {
System.out.println("经过之后验证");
}
/**
* 处理完请求后执行
*/
@AfterReturning(pointcut = "@annotation(vip.hblg.iot.annotation.CheckPreAuthorize)")
public void doAfterReturning() {
System.out.println("处理之后");
}
/**
* 拦截异常操作
*/
@AfterThrowing(value = "@annotation(vip.hblg.iot.annotation.CheckPreAuthorize)")
public void doAfterThrowing() {
System.out.println("处理发生异常时");
}
}
4.在方法上使用
@CheckPreAuthorize
@GetMapping("findAllEntityList")
public List<Entity> findAllEntityList() {
return entityService.findAllEntityList();
}
5.执行顺序
经过之前验证
处理之后
经过之后验证
版权声明:本文为weixin_42600788原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。