场景:
aop切片编程应该是众所周知的,但aspect可以方便开发人员为请求指定拦截层。 一般来说,根据条件切入控制器控制层,进行认证、注释分析、获取类名方法名参数、记录操作日志等
引入 aop 依赖包:
! -依赖关系,如切面编程@Aspect、@ pointcut-- dependencygroupidorg.spring framework.boot/groupidartifactidspring-boot-sspring
切入流程:
1、创建组件类并标记注释@Aspect
2、定义切口标注注释@Pointcut
3、使用切口切入标记注释@Before或@After
代码案例:
package com.hkl.modules.aspect; import com.hkl.annotation.field convert; import lombok.extern.slf4j.slf4j; importorg.AspectJ.lang.join point; importorg.AspectJ.lang.annotation.after; importorg.AspectJ.lang.annotation.aspect; importorg.AspectJ.lang.annotation.before; importorg.AspectJ.lang.annotation.pointcut; importorg.AspectJ.lang.reflect.methodsignature; importorg.spring framework.stereotype.com ponent; importorg.spring framework.web.context.request.requestcontextholder; importorg.spring framework.web.context.request.servletrequestattributes; import javax.servlet.http.http servlet请求; import java.lang.reflect.Method;/* * * pclass name:AOP configure/p * p description :切入项目的控制层配置类/p * pdate:2021/11/26/p */@ component . controller.* (. ) */@指定pointcut (execution ) com.hkl.modules.controles/* *指定注释的切入* @ param @pointcut ) ) @annotation )只有在同时满足com.hkl.annotation.field convert { }/* * * *方法之前切入控件层的*表达式和注释方法时@before(value='getmethods () withAnnotationMethods () () ) ) ) publicvoiddobefore (连接点连接点) 获取servlet容器servletrequestattributes=) servletrequestattributes (请求属性)的请求httpservletrequestrequestrequestrequest请求//执行方法对象methodsignaturesignature=(methodsignature ) joinPoint.getSignature ); 方法方法=signature.get method (; //判断切入方法是否标记xxx注释//boolean flag=method.isannotationpresent (XXX.class )//collutil.tolist(role /**操作说明start *///1、认证、对请求对象设定的属性的分析//2、反射分析注释、操作日志的记录等/**操作说明end */log.info (测试切入{} )成功方法名称: ' method.) } /*** *方法运行后,只有同时满足切入控件层的*表达式和注释方法,* @ param join point */@ after (value=' get publicvoiddoafter (连接点连接点)//业务操作是@Before方式methodsignaturemethodsignature=) methodsignature ) join point.ggggnature log.info ()测试成功。 包括评论吗? (method.isannotationpresent ) fieldconvert.class )、) @After ); log.info (注释的属性值) method.get annotation (field convert.class ).codeType ) ); }} 测试代码:
@fieldconvert(codetype='aa ') API operation (value='测试切面用' ) get mapping (value='/gettestaop ' ) commonresuls ); } 测试结果成功切入:
总结和注意:
1、定义切口,支持指定包按路径切入,也支持指定是否标记某个注释的切口
2、aop默认情况下无法切入private修饰的方法。 切口表达式定义的修饰符必须与切入的方法修饰符匹配才能切入
3、根据以下切入点规则,有切入公共修饰或省略修饰符的方法,推荐使用这种方式
@pointcut(execution ) com.hkl.modules.controller.* ) )、@pointcut(execution ) public*com )时