在项目中我们经常需要记录接口的访问日志;那么就要在实现接口功能代码的同时还需要添加访问日志的代码,访问日志的代码基本都差不多;有没有可能将这部分代码封装起来在需要记录访问日志的接口中无侵入的添加进去呢?答案是可以的。
可以使用自定义注解的方式将访问日志的代码无侵入添加到我们的接口中;这里就需要用到spring AOP和自定义注解来实现。
以下为实现过程:
1pom.xml配置
org.springframework.boot
spring-boot-starter-aop
2新建自定义注解operationLog
/**
* 操作日志注解
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {
String operation();//操作名称
String bo();//操作对象
String id() default "";//操作数据ID
}
3通过切面实现记录日志的功能
/**
* 操作日志切面
*/
@Aspect
@Component
public class OperationLogAspect {
@Resource
private OrgLogService orgLogService;
@Pointcut("@annotation(com.binkai.annotation.log.OperationLog)")
private void optionLogCheck(){
}
@After("optionLogCheck()")
public void optionLogLast(JoinPoint joinPoint){
MethodSignature methodSignature= (MethodSignature) joinPoint.getSignature();
//获取方法的参数名和参数值
List argNames= Arrays.asList(methodSignature.getParameterNames());
List
4在需要记录访问日志的接口中使用这个注解
@GetMapping("/{bo}/del/{id}")
@ResponseBody
@OperationLog(operation = "del",bo="#{bo}",id="#{id}")
public Result delete(@PathVariable("bo") String bo,
@PathVariable("id") String id){
int res=businessService.deleteById(bo,id);
return Result.OK();
}
以上只是自定义注解的使用场景之一;其实通过自定义注解我们可以实现如验证权限、验证token等很多类似的功能
页面更新:2024-04-05
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号