Spring中通过注解给返回值加状态信息

来源:互联网 发布:按揭贷款月供怎么算法 编辑:程序博客网 时间:2024/06/16 02:54

在JavaWeb开发中,我们时常需要给返回到前端的数据加上一些头部的状态信息,如下的codemsg

{    "code": "SUCCESS",    "msg": "操作成功",    "roleInfo": {        "roleId": 1,        "roleCode": "ITManager",        "roleName": "IT部门管理员",        "enabledFlag": "Y",        "createdBy": "张伟",    }}

我们就需要一个BaseHelper来存储这些值

public class BaseHelper<T> {    private String code;    private String msg;    private T data;    //其他的get set toString 方法略}

在返回数据的时候,我们就有两种方法来设置我们的返回数据
一种就是手动的在业务逻辑层或者控制器添加。
还有一种就是要介绍的通过注解给返回值加上状态信息

注解定义如下

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface RestWrapper {    String code() default StatusInfoUtils.SUCCESSCODE;    String msg() default StatusInfoUtils.SUCCESSMSG;}

上面代码的StatusInfoUtils工具类的定义如下

public final class StatusInfoUtils {    private StatusInfoUtils(){}    //返回状态信息    public static final String SUCCESSCODE="SUCCESS";    public static final String SUCCESSMSG="操作成功";    public static final String FAILCODE="FAIL";    public static final String FAILMSG="操作失败";}

接下来我们就要继承AbstractMappingJacksonResponseBodyAdvice并重写一个切面方法beforeBodyWriteInternal,然后就可以对返回的数据进行封装了。

如下代码

@RestControllerAdvicepublic class GlobalControllerAdvice extends AbstractMappingJacksonResponseBodyAdvice {    /**     * 后处理,在方法有RestWrapper注解时,包装return type     */    @Override    protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer,                                           MediaType contentType, MethodParameter returnType,                                           ServerHttpRequest request, ServerHttpResponse response) {        if (returnType.getMethod().isAnnotationPresent(RestWrapper.class)) {            bodyContainer.setValue(getWrapperResponse(returnType,request,                    bodyContainer.getValue()));        }    }    private BaseInfo getWrapperResponse(MethodParameter returnType,                                        ServerHttpRequest req,                                        Object data) {        RestWrapper wrapper=returnType.getMethod().getAnnotation(RestWrapper.class);        return new BaseHelper(wrapper.code(), wrapper.msg(), data);    }}

定义好这个之后我们就可以愉快的使用我们自定义的这个注解来包装我们返回的数据了

如下使用

    /**     * 测试.     *     * @return the attachment info     */    @ResponseBody    @RequestMapping(value = {"test"})    @RestWrapper(msg = StatusInfoUtils.GETSUCCESS)    public List<Employee> test() {        List<Employee> employeeList=new ArrayList<>();        Employee employee=new Employee();        employee.setCnName("黄飞鸿");        employeeList.add(employee);        return employeeList;    }

看看运行之后的返回数据

{    "code": "SUCCESS",    "messages": "成功",    "data": [        {            "empUid": null,            "cnName": "黄飞鸿"        }    ]}

OK,这样我们就完成了一个通过注解封装返回数据的功能。


2017-11-21 10:49 于 上海