关于spring:Spring-AOP

3次阅读

共计 1511 个字符,预计需要花费 4 分钟才能阅读完成。

面向切面编程 (AOP) 是 Spring 的两大外围之一.AOP 的思维能够帮忙咱们在不侵入代码的状况下对原有性能进行加强, 批改;

大抵是以下流程

反射 -> proxy(动静代理) -> AOP(面向切面)

@Aspect

*   定义切面类

@Pointcut

*   切点

Advice

*   在切入点上执行的加强解决
*   @Before
*   @After
*   @AfterReturning 切点办法拿到返回值后执行
*   @AfterThrowing 切点办法抛出异样后执行
*   @Around 盘绕加强

失常的执行程序是:@Around ->@Before-> 主办法体 ->@Around 中 pjp.proceed()->@After->@AfterReturning
@Around
如果不执行 proceedingJoinPoint.proceed()办法,那么指标办法不会执行;
能够决定是否执行指标办法;@before 只是拦挡办法; 如果加了 @around, 原办法交给 proceed()管制
//xx()是切点
@Around("xx()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{log.info("进入 around")
       return proceedingJoinPoint.proceed();}
语法规定
  • 反对 &&,||,!
  • @Pointcut(execution(url)) 指定切面办法
  • @Pointcut(“@annotation(url)”) 自定义注解指定切面办法
  • within,this,target…

demo

spd 零碎中应用 aop 对向外提供的 api 接口进行 token 校验权限管制.

1. 首先自定义注解并在须要权限认证的接口上加上注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReportPermission {}

2.

@Component
@Aspect
@Slf4j
public class OrderReportAspect {

@Autowired
private ISysUserService sysUserService;

@Pointcut("@annotation(com.x.common.annotation.ReportPermission)")
 public void pointCut() {} 
 
// 依据角色管制容许拜访接口的用户
@Around("pointCut()")
 public Object before(ProceedingJoinPoint pjp) throws Throwable {Object[] in = pjp.getArgs();

 if (in.length >= 1) {HttpServletRequest request = (HttpServletRequest) in[0];
  log.info("切面获取 request:{}",request);
  String userId = JwtUtil.checkToken(request.getHeader("token"));
  // 校验以后 userId 是否有读取接口的权限
  int count = sysUserService.isSpecified(userId,Constant.LOGISTICS_REPORT_RECEIVER);
 
 if (count == 1) {return pjp.proceed();}
 log.warn("api 接口角色校验失败");
 return null;
 }
 log.warn("api 接口角色校验失败");
 return null;
 }
}
正文完
 0