面向切面编程(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@Slf4jpublic class OrderReportAspect {@Autowiredprivate 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; }}