统一返回格式
必须规避
- 避免使用字符串响应前端
- 避免使用Map进行上下文传递与前端交互
除重定向以外,不得返回void,只需要返回code和message的时候,可以使用
Response<Void>规范做法
定义一个Response
等类似的工具,响应前端的数据. @Datapublic class Response<T> implements Serializable {//需要团队统一code的返回信息.private Integer code;private String message;private Boolean success;private T data;//可以辅助一些静态方法来减少new Response()的情况}
尽量使用Bean来接受前端参数
规避
- 多个参数(超过3个)作为方法形参。
3个以及3个以上的形参应该改造成Bean对象的形式进行传递。且形参尽量和业务强关联,避免出现与业务无关的输入参数,不得出现用户信息,i18n等等信息。
在业务发展需要额外添加参数的时候改动较大.
Bad 案例
//6个形参, 占用了大量篇幅. 久而久之会加大理解难度.public BaseResultForm insertMongo(String businessId, Integer appId, Integer industryId, String businessName,Integer isPublic, Integer appSceneId) {//使用Map作为返回值. 阅读理解上不适用于团队写作,应该修改Bean返回.Map<String, Object> resultMap = reviewStateService.insertMongo(businessId, appId, industryId, businessName, isPublic, appSceneId);BaseResultForm baseResultForm = new BaseResultForm();baseResultForm.setData(resultMap);return baseResultForm;}
Good 案例
@GetMapping("insertIntoMongo")public Response<InsertMongoResponse> insertMongo(InsertMongoRequest insertMongoRequest) {InsertMongoResponse insertMongoResponse = reviewStateService.insertMongo(insertMongoRequest);return Response.success(insertMongoResponse);}
参数传递与判断
- Response 是Controller层专用的. 只是用于包装响应参数,不得将其传递到
Service层 - Controller层做参数转换,不得向后传递Map或者是JSON字符串。同理Service的响应也不能返回Map和JSON字符串
- 参数中尽量不要出现HttpServletRequest以及HttpServletResponse,如有需要可以从上下文中获取。
- 多利用
@RequestParam等进行校验. 减少Controller层if判断的出现. - 多利用全局异常
@ControllerAdvice和@ExceptionHandler,减少Controller层try catch块的出现. - 尽量将Controller的日志在AOP中收集. 减少每一个Controller方法.一个
logger.info,日志集中体现在Service中
上下文参数传递
与业务无关的上下文参数传递尽量依赖ThreadLocal.
由于继承了HashMap,传递性更强.
public class RequestContext extends HashMap<String, Object> {private static final ThreadLocal<RequestContext> LOCAL = new ThreadLocal<>();protected RequestContext() {}public static void init() {LOCAL.set(new RequestContext());}public static RequestContext getContext() {return LOCAL.get();}public static void clean() {LOCAL.remove();}//========================================================public void setAppInfo(AppInfo appInfo) {put("AppInfo", appInfo);}public AppInfo getAppInfo() {return (AppInfo) get("AppInfo");}//========================================================}
