springboot @Aspect 切面接口
好久没写文章了 更新一个小技术点关于@Aspect 切面接口的应用,不多说上代码
@Slf4j
@Aspect
@Component
public class InterceptorAspect {
@Pointcut("execution(public * com.www.baidu.job..*.*(..))")
public void Pointcut() {
}//签名
@Before(value = "Pointcut()")
public void logBeforeController(JoinPoint joinPoint) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
// 记录下请求内容
log.info("已经进入Aspect---Before----- : ", StringUtils.join(joinPoint.getArgs(), ";"));
}
@AfterReturning(value = "Pointcut()", returning = "rvt")
public void after(JoinPoint joinPoint, Object rvt) {
log.info("已经进入Aspect--after----- : ");
//获取类型参数,获取注解中的参数
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
InserVolumeAspect action = method.getAnnotation(InserVolumeAspect.class);
log.info("类型:" + action.type());//通过反射获得注解上的属性 然后做相关操作
//下面就是获取该接口的返回参数
MethodSignature sig1 = (MethodSignature) joinPoint.getSignature();
Method method1 = sig1.getMethod();
if (null != rvt && null != method1.getDeclaringClass()) {
try {
log.info("{} . {} : 返回数据:{}", method1.getDeclaringClass().getName(), method1.getName(), new Gson().toJson(rvt));
} catch (Exception e) {
}
}
}
}
这就是关于aop切面的应用,也可以做系统接口的日志,里边参数的意思百度下都有 简单说下 after函数是方法接口执行完在执行的函数 before是进入方法先执行,比如做成切面的日志接口就可以使用before函数
最后提醒应用者重要的一点 这个自定义注解可以不标注在controller上 但是 AfterReturning返回的参数依然使你controller的返回值
还没有评论,来说两句吧...