- 注解类
package com.two.elements.annontation;
import java.lang.annotation.*;
/**
* 检查参数
*
* @author
* @version 1.0
* @date 2019-03-03 02:14:00
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CheckParameter {
/**
* 接口名称
*/
String apiName() default "";
}
代码
package com.two.elements.annontation;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.two.elements.util.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* @author
* @version 2019-02-01
*/
@Aspect
@Component
public class CheckParameterAspect {
private static final Logger logger = LoggerFactory.getLogger(CheckParameterAspect.class);
@Around("@annotation(checkParameter)")
public Object checkParameter(ProceedingJoinPoint joinPoint, CheckParameter checkParameter) throws Throwable {
StopWatch watch = new StopWatch();
watch.start();
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
String apiName = checkParameter.apiName();
String method = request.getMethod();
String url = request.getRequestURL().toString();
String ip = IpUtil.getIpAddr(request);
String userAgent = request.getHeader("User-Agent");
String params = "";
try {
params = new ObjectMapper().writeValueAsString(joinPoint.getArgs()[0]);
} catch (Exception ex) {
ex.printStackTrace();
}
logger.info("\n------{}------\nURL:{}\nMethod:{}\nIP:{}\nParams:{}\nUser-Agent:{}\n-------------------- 分割线 --------------------",
apiName, url, method, ip, params, userAgent);
Object result = joinPoint.proceed();
watch.stop();
logger.info("返回数据:{}", result);
logger.info("{}耗时:{}毫秒", apiName, watch.getTotalTimeMillis());
return result;
}
}
切片类
org.aspectj.lang.annotation.Around
org.aspectj.lang.annotation.Aspect
- 调用
@CheckParameter(apiName = "xxx")
@RequestMapping...