@Aspect
@Component
@Slf4j
public class LogAspect {
@Pointcut("execution(* com.ht.controller..*.*(..))")
private void controllerAspect() {
}
*/
* 请求入口
*
* @param joinPoint
*/
@Before(value = "controllerAspect()")
public void beforeHandle(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
log.info("=========================REQUEST CONTENT START=========================");
try {
log.info("request method and url:{} , {}", request.getMethod(), request.getRequestURL().toString());
log.info("request header:{}", JSON.toJSONString(getRequestHeaderMap(request)));
log.info("request param:{}", Arrays.toString(joinPoint.getArgs()));
log.info("类路径,方法名 :{},{} ", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
} catch (Exception e) {
log.error("beforeHandle", e);
}
log.info("=========================REQUEST CONTENT END===========================");
}
}
*/
* 请求出口
*
* @param response
*/
@AfterReturning(returning = "response", value = "controllerAspect()")
public void afterHandle(Object response) {
if (response != null) {
log.info("=========================RESPONSE CONTENT START========================");
log.info("response content is:{}", JSONObject.toJSONString(response));
log.info("=========================RESPONSE CONTENT END==========================");
}
}
private Map<String, String> getRequestHeaderMap(HttpServletRequest request) {
Map<String, String> header = new HashMap<>(16);
Enumeration<String> enums = request.getHeaderNames();
while (enums.hasMoreElements()) {
String headerParam = enums.nextElement();
header.put(headerParam, request.getHeader(headerParam));
}
return header;
}
}
总结:
- 使用@Aspect将POJO声明为切面;
- 在切面类中使用@Pointcut进行命名切入点声明;
- 定义通知方法,使用5中注解声明,其中value用于定义切入点表达式或引用命名切入点;
- 配置文件需要使用<aop:aspectj-autoproxy/来开启注解风格的@AspectJ支持;
- 将切面类和POJO类注册到Spring容器中