基础了解
首先需要知道几个注解
@Pointcut
概念:spring aop切点
举例:
//当使用到QhLog这个类时,会切入切点
@Pointcut("@annotation(net.qh.common.annotation.QhLog)")
public void qhLog(){
log.info("---注入用户操作日志切面---");
}
@Around
概念:通俗来说是调用@Pointcut 中的方法
举例:
@Around("qhLog()")
步骤:
- 创建日志注解类
- 编写切面方法
- 在控制层引用
具体实现
1. 创建日志注解类
package net.qh.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface QhLog {
String module() default "";
String ot() default "";
String summary() default "";
}
2. 编写切面方法
@Aspect
@Component
@Slf4j
public class LogAspect {
@Pointcut("@annotation(net.qh.common.annotation.QhLog)")
public void qhLog(){
log.info("---注入用户操作日志切面---");
}
@Around("qhLog()")
public Object interfaceProcess(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("---切面开始执行---");
Object[] args = joinPoint.getArgs();
// 在joinPoint.proceed()前先获取参数,防止在方法参数被修改
String params = argsArrayToString(args);
Object respResult = joinPoint.proceed(args);
handleLog(joinPoint, params, null, respResult);
return respResult;
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "qhLog()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
Object[] args = joinPoint.getArgs();
String params = argsArrayToString(args);
handleLog(joinPoint, params, e, null);
}
protected void handleLog(final JoinPoint joinPoint, String params, final Exception e, Object result) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
QhLog qhLog = signature.getMethod().getAnnotation(QhLog.class);
OperLog operLog = new OperLog();
//这种就是控制层传进来的值
operLog.setModule(qhLog.module());
operLog.setOperType(qhLog.ot());
// 请求的地址
String ip = IpUtils.getIpAddr(request);
operLog.setOperIp(ip);
operLog.setOperUrl(request.getRequestURI());
// 返回参数
operLog.setResult(JSON.toJSONString(result));
}
}
3. 在控制层引用
@QhLog(module = "套餐", ot = "修改", summary = "修改软件套餐")
@PutMapping
public R update(@RequestBody Soft soft){
return softService.update(soft);
}