Spring中通過註解給返回值加狀態信息

在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,然後就可以對返回的數據進行封裝了。

如下代碼

@RestControllerAdvice
public 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 於 上海

發佈了179 篇原創文章 · 獲贊 230 · 訪問量 56萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章