- 开启AOP切面配置
@Configuration
@ComponentScan(basePackages = "com.spring")
@EnableAspectJAutoProxy
public class ApplicationContextConfig {
}
- 切面类
@Component
@Aspect
public class AopAspect {
private static Logger logger = LoggerFactory.getLogger(AopAspect.class);
@Pointcut("execution(public * com.spring.service..*.*(..)))")
public void serviceImplClass() {
}
@Pointcut("@within(org.springframework.stereotype.Service)")
public void serviceAnnotation() {
}
@Pointcut("!within(com.counter.wmb.IEsbHandleService+)")
public void excludeTarget() {
}
@Around("excludeTarget() && (serviceImplClass() && serviceAnnotation())")
public Object around(ProceedingJoinPoint pjp) {
Method targetMethod = this.getTargetMethod(pjp);
try {
this.printInputParamsLog(pjp, targetMethod);
return pjp.proceed();
} catch (Throwable e) {
String errorMsg = this.printErrorLog(targetMethod, e);
return Response.failure(errorMsg);
} finally {
TraceLogUtil.clear();
}
}
private void printInputParamsLog(ProceedingJoinPoint pjp, Method targetMethod) {
String logMsg = "%s input params:[%s]";
TraceLogUtil.info(logger, String.format(logMsg, this.getSimpleTargetMethodName(targetMethod), this.getParamsStr(pjp, targetMethod)));
}
private String printErrorLog(Method targetMethod, Throwable throwable) {
String errorMsg = "%s error:%s";
errorMsg = String.format(errorMsg, this.getSimpleTargetMethodName(targetMethod), throwable.getMessage());
TraceLogUtil.error(logger, errorMsg, throwable);
return errorMsg;
}
private String getParamsStr(ProceedingJoinPoint pjp, Method targetMethod) {
ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
String[] parameterNames = pnd.getParameterNames(targetMethod);
Object[] args = pjp.getArgs();
List<String> paramList = new ArrayList<>();
for (int i = 0, length = parameterNames.length; i < length; i++) {
paramList.add(parameterNames[i] + "=" + JacksonUtil.toJSONString(args[i]));
}
return StringUtils.join(paramList, ",");
}
private Method getTargetMethod(ProceedingJoinPoint pjp) {
try {
Signature signature = pjp.getSignature();
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("Spring AOP point cut error,only can point cut in method!");
}
MethodSignature methodSignature = (MethodSignature) signature;
Object target = pjp.getTarget();
return target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private String getSimpleTargetMethodName(Method targetMethod) {
return targetMethod.getDeclaringClass().getSimpleName() + "." + targetMethod.getName() + "(..)";
}
}