在项目中我们经常需要记录接口的访问日志;那么就要在实现接口功能代码的同时还需要添加访问日志的代码,访问日志的代码基本都差不多;有没有可能将这部分代码封装起来在需要记录访问日志的接口中无侵入的添加进去呢?答案是可以的。 可以使用自定义注解的方式将访问日志的代码无侵入添加到我们的接口中;这里就需要用到springAOP和自定义注解来实现。 以下为实现过程: 1pom。xml配置!切面依赖dependencygroupIdorg。springframework。bootgroupIdspringbootstarteraopartifactIddependency 2新建自定义注解operationLog操作ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a注解Target({ElementType。METHOD})Retention(RetentionPolicy。RUNTIME)DocumentedpublicinterfaceOperationLog{Stringoperation();操作名称Stringbo();操作对象Stringid()操作数据ID} 3通过切面实现记录日志的功能操作ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a切面AspectComponentpublicclassOperationLogAspect{ResourceprivateOrgLogServiceorgLogSPointcut(annotation(com。binkai。annotation。log。OperationLog))privatevoidoptionLogCheck(){}After(optionLogCheck())publicvoidoptionLogLast(JoinPointjoinPoint){MethodSignaturemethodSignature(MethodSignature)joinPoint。getSignature();获取方法的参数名和参数值ListStringargNamesArrays。asList(methodSignature。getParameterNames());ListObjectargValuesArrays。asList(joinPoint。getArgs());将方法的参数名和参数值一一对一放入上下文中EvaluationContextcontextnewStandardEvaluationContext();for(inti0;iprepdatatrack124在需要记录访问ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a的接口中使用这个注解precodeGetMapping({bo}del{id})ResponseBodyOperationLog(operationdel,bo{bo},id{id})publicResultdelete(PathVariable(bo)Stringbo,PathVariable(id)Stringid){intresbusinessService。deleteById(bo,id);returnResult。OK();} 以上只是自定义注解的使用场景之一;其实通过自定义注解我们可以实现如验证权限、验证token等很多类似的功能