工作中实现记录接口调用的注解例子
Posted unclewang001
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工作中实现记录接口调用的注解例子相关的知识,希望对你有一定的参考价值。
本例编写了一个作用于方法之上的自定义注解,主要作用是记录方法的入参以及返回结果
1.自定义一个注解
/** * 需要切的方法 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface RequestLogAnnotation { // 操作的业务类型 public String value() default ""; }
2.注解定义好了,我们就需要编写一个能处理上面注解的处理类
@Aspect
@Component
public class RequestLogAspect {
public final static Logger logger = LoggerFactory.getLogger(RequestLogAspect.class);
@Pointcut("@annotation(com.***.***.***.service.aspect.RequestLogAnnotation)")//上面注解的包路径
public void requestLogPointcut() {
}
@Autowired
private PerfRequestLogMapper perfRequestLogMapper; //自定义的一个dao
@Around("requestLogPointcut()")
public Object process(ProceedingJoinPoint point) {
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
String requestParam = logRequestParam(point);
PerfRequestLogDO perfRequestLogDO = new PerfRequestLogDO();
perfRequestLogDO.setRequestParam(requestParam);
perfRequestLogDO.setRequestMethod(method.getName());
Object result = null;
try {
result = point.proceed();
if (Objects.isNull(result)){
return result;
}
perfRequestLogDO.setResponseResult(JSON.toJSONString(result));
perfRequestLogMapper.insertSelective(perfRequestLogDO);
} catch (Exception e) {
logger.error("切面处理失败_Exception:{}", e);
} catch (Throwable e) {
logger.error("切面处理失败_Exception:{}", e);
}
return result;
}
private static String logRequestParam(ProceedingJoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
StringBuilder arguments = new StringBuilder();
for (Object arg : args) {
arguments.append(arg.getClass().getSimpleName());
if (arg == null) {
continue;
}
arguments.append("=").append(Objects.isNull(arg) ? "NULL" : arg.toString());
}
return arguments.toString();
}
}
3.入库dao
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.**.**.**.dao.saleperf.entity.PerfRequestLogDO" useGeneratedKeys="true"> insert into perf_request_log <trim prefix="(" suffix=")" suffixOverrides=","> <if test="requestMethod != null"> request_method, </if> <if test="requestParam != null"> request_param, </if> <if test="responseResult != null"> response_result, </if> <if test="erroMessage != null"> erro_message, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="requestMethod != null"> #{requestMethod,jdbcType=VARCHAR}, </if> <if test="requestParam != null"> #{requestParam,jdbcType=VARCHAR}, </if> <if test="responseResult != null"> #{responseResult,jdbcType=VARCHAR}, </if> <if test="erroMessage != null"> #{erroMessage,jdbcType=VARCHAR}, </if> </trim> </insert>
以上是关于工作中实现记录接口调用的注解例子的主要内容,如果未能解决你的问题,请参考以下文章
ASP.net MVC 代码片段问题中的 Jqgrid 实现