我们在提供 API json 数据接口时每个接口都需要返回 {code : 0,status:200,message:"",result:{} }之类的数据这些数据是重复的,我们可以利用Spring的AOP 去添加这些数据,Controller 中只返回有用的数据,如参数之类的错误可以直接返回null ,如有需要提示APP页面弹出的信息,直接加入到 result json 对象中 交给AOP 去格式化这个数据
1. SpringBoot 项目引入AOP
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 创建AOP类
@Aspect
@Component
public class ResultAop {
private static final Logger log = LoggerFactory.getLogger(ResultAop.class);
private final String pointcutStr = "execution( * com.khsct.controller..*.*(..))";
@Pointcut(pointcutStr)
public void excuteController() {
}
@AfterReturning(value = pointcutStr, returning = "jobj")
public JSONObject doAroundAdvice(JoinPoint joinPoint, JSONObject jobj) {
// proceedingJoinPoint.getArgs();
try {
// obj之前可以写目标方法执行前的逻辑
procesResultObj(jobj);
return jobj;
} catch (Throwable throwable) {
throwable.printStackTrace();
log.error("@AfterReturning 出错{}", throwable.getMessage());
}
return null;
}
/**
* 处理返回对象
*/
@SuppressWarnings("unused")
private void procesResultObj(JSONObject obj) {
if (obj != null) {
String message = (String) obj.get(CommonConst.DEFAULT_MSG_POP_KEY);
Integer code = ErrorCode.LOGIC_SUCCESS.getName();
if (message != null) {
code = ErrorCode.POP_MSG_CODE.getName();
obj.remove(CommonConst.DEFAULT_MSG_POP_KEY);
} else {
message = ErrorMesg.Success.getName();
}
String str = JSON.toJSONString(obj);
obj.clear();
obj.put(CommonConst.DEFAULT_RESULT_STATUS_KEY, ErrorCode.SUCCESS.getName());
obj.put(CommonConst.DEFAULT_RESULT_CODE_KEY, code);
obj.put(CommonConst.DEFAULT_MSG_POP_KEY, message);
obj.put(CommonConst.DEFAULT_RESULT_DATA_KEY, JSON.parseObject(str));
}else{
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
try {
response.setCharacterEncoding(CommonConst.CHARACTER_ENCODING);
response.setContentType(CommonConst.CONTENT_TYPE);
ServletOutputStream out = out = response.getOutputStream();
JSONObject o = new JSONObject();
o.put(CommonConst.DEFAULT_RESULT_CODE_KEY, ErrorCode.FAILED.getName());
o.put(CommonConst.DEFAULT_RESULT_STATUS_KEY, ErrorCode.SUCCESS.getName());
o.put(CommonConst.DEFAULT_MSG_POP_KEY, ErrorMesg.Parameters_Error.getName());
out.write(o.toString().getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
log.error(" 返回值为 null 获取 response.getOutputStream 出错 ");
}
}
}
}
3. 在SpringBoot 启动类上加上注解开启AOP
@EnableAspectJAutoProxy(proxyTargetClass = true)
4. 创建 Controller 返回值必须要与AOP中 doAroundAdvice 定义的类型一致 或者是他的子类此处统一使用alibaba 的fastJson JSONObject 对象
@PostMapping(value = "/test")
public JSONObject test(String adminHeadImage, HttpServletRequest request) {
JSONObject data = null;
if(StringUtils.isNotBank(adminHeadImage)){
data = new JSONObject();
//data.put(key,value);
}
return data;
}
结果如下:
{
"code": 1,
"data": {},
"message": "ok",
"status": 200
}