SpringBoot AOP实现拦截接口请求与响应结果


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.***.****.common.ResponseBean;

@Aspect
@Component
public class LoggerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);

	@Around("execution(* com.xxx..*..*.*Controller.*(..))")
	public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
		ObjectMapper obj = (new ObjectMapper()).disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		StringBuffer method = new StringBuffer();
		method.append(joinPoint.getTarget().getClass().getSimpleName()).append(".");
		method.append(joinPoint.getSignature().getName()).append("#");
		StringBuffer buffer = new StringBuffer();
		buffer.append(method);
		Object[] arguments = joinPoint.getArgs();
		Object[] result = arguments;
		int arg6 = arguments.length;

		for (int arg7 = 0; arg7 < arg6; ++arg7) {
			Object arg = result[arg7];
			if (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)
					&& !(arg instanceof MultipartFile) && !(arg instanceof MultipartFile[])) {
				buffer.append(obj.writeValueAsString(arg));
			}
		}

		log.info("request#{}", buffer.toString());
		Object arg9 = joinPoint.proceed();
		String resultMessage = getResultMessage(obj,arg9);
		log.info("resultMessage#{}", resultMessage);

		return arg9;
	}
	private String getResultMessage(ObjectMapper obj, Object result) {
		String resultStr = null;

		try {
			if (result instanceof ResponseBean) {
				resultStr = obj.writeValueAsString(result);
				return resultStr;
			} else {
				return obj.writeValueAsString(result);
			}
		} catch (Exception arg4) {
			return "";
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值