文章目录

案例:对返回参数的time类型判断

比如,我们需要对返回参数的时间类型进行替换,如果是一个无意义的时间,把它置为null!

正常的​​Controller​

@PostMapping("/getReceivableDetail")
public BaseResp<PageInfo> getProfitReportByOrder(@RequestBody @Validated SettlementDetailRequest request) {
//统一返回结果BaseResp
return BaseResp.success(xxxService.getReceivableDetail(request));
}

使用AOP拦截返回,对参数做处理

@Slf4j
@Aspect
@Component
public class InvalidTimeClearAspect {

private static List<LocalDateTime> invalidTimes = new ArrayList<>();

static {
invalidTimes.add(LocalDateTime.of(1900, 1, 1, 0, 0, 0));
invalidTimes.add(LocalDateTime.of(1970, 1, 1, 0, 0, 0));
}

/**
* 仅切入Shopee控制器
*/
@Pointcut("execution(* cn.xx.xx.xx.web.controller.finance.ShopeeAccountCheckController.*(..))")
public void shopeeAccountCheck() {
}

@Pointcut("execution(* cn.xx.xx.xx.web.controller.finance.ShopeeFinancesEscrowController.*(..))")
public void shopeeFinancesEscrow() {
}

@Pointcut("execution(* cn.xx.xx.xx.web.controller.finance.ShopeeReportController.*(..))")
public void shopeeReport() {
}

@Pointcut("shopeeAccountCheck() || shopeeFinancesEscrow() || shopeeReport()")
public void dateFormatPointCut() {
}


//在返回之后切入dateFormatPointCut
@AfterReturning(value = "dateFormatPointCut()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) throws IllegalAccessException, InstantiationException {

if (!(result instanceof BaseResp)) return;

BaseResp resp = (BaseResp) result;

if (!(resp.getData() instanceof PageInfo)) return;

PageInfo<?> pageInfo = (PageInfo) resp.getData();

//泛型获取返回结果中的data数据
List<?> list = pageInfo.getList();

if (ObjectUtils.isEmpty(list)) return;

for (Object o : list) {
//反射获取返回date中的属性
Field[] fields = o.getClass().getDeclaredFields();
for (Field field : fields) {
//获取属性类型
String typeName = field.getType().getName();
if ("java.time.LocalDateTime".equals(typeName)) {
field.setAccessible(true);
//如果属性类型是时间类型,取出属性的值
Object val = field.get(o);
if (ObjectUtils.isEmpty(val)) continue;
LocalDateTime oriVal = (LocalDateTime) val;
for (LocalDateTime invalidTime : invalidTimes) {
//如果属性值是一个无效时间,置为null
if (invalidTime.equals(oriVal)) {
field.set(o, null);
}
}
}
}
}
}
}