0
点赞
收藏
分享

微信扫一扫

StaticMethodMatcherPointcutAdvisor静态切入点实现切面


通过注解实现接口的日志记录,是aop的一大用处。

  • 实现注解

/**
* @Description Accesslog:
* @Author LiHaitao
* @Date 2018/12/21 15:37
**/


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLogger {
String description() default "";

}

  • 测试接口

/**
* Created by Administrator on 2019/7/26.
*/
@RestController
@RequestMapping("/student")
public class StudentController {

@Autowired
private StudentService studentService;


@GetMapping(path = "/ok")
@SystemLogger(description = "查询学生") //注解方法处
public String select() {
return "ok";
}
}

  • aop实现

@Component
public class AopLogService extends StaticMethodMatcherPointcutAdvisor {

public AopLogService() {
this.setAdvice((MethodInterceptor) (methodInvocation) -> {
Object proceed;
Log log = null;
try {
log = this.createLog(methodInvocation);
proceed = methodInvocation.proceed();
//这里将日志Log保存或者通过事件机制通知,异步进行处理
} catch (Throwable a) {
throw a;
}
return proceed;
});
}

private Log createLog(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
Object aThis = invocation.getThis();
SystemLogger methodAnnotation = AopUtil.findMethodAnnotation(aThis.getClass(), method, SystemLogger.class);
String description = methodAnnotation.description();
Log log = new Log();
log.setDescp(description);
log.setMethod(method.getName());


Object[] arguments = invocation.getArguments();
for (Object argument : arguments) {
if (argument instanceof NewStudentRequest) {
System.out.println("ok----------------");
}
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String requestURI = request.getRequestURI();
log.setUrl(requestURI);
return log;

}


@Override
public boolean matches(Method method, Class<?> aClass) {
SystemLogger annotation = AopUtil.findAnnotation(aClass, method, SystemLogger.class);
return annotation != null;
}

matches方法来判断是否切入,true为切入,false不切入。


举报

相关推荐

0 条评论