轉載自:http://www.5180it.com/bbs/admin/1/117237.html
記一個springboot項目攔截接口相應資料,并自定義修改資料内容的方法
在我們開發過程和前端聯調資料,往往都沒有好的測試資料,每次都做假的資料就太麻煩了,特别是一些報表資料。
現在分享一個可以自定義傳回資料的方法,直接上代碼
package com.yy.auth;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import com.yy.bs.demo.demodata.DemoDataService;
import com.yy.domain.bs.demo.demodata.DemoDataEntity;
import com.yy.frame.auth.handler.UserInfoThreadLocal;
import com.yy.modules.sys.param.ParamUtil;
import com.yy.modules.sys.user.UserInfo;
@ControllerAdvice
public class ResponseBodyAnalysis implements ResponseBodyAdvice<Object> {
@Autowired
private DemoDataService demoDataService;
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
try {
UserInfo curUser = UserInfoThreadLocal.getInstance().get();
if(curUser != null && curUser.getOrgid().equals(ParamUtil.getParamValue("demo_orgid", "1735292260538819520"))){
List<DemoDataEntity> list = demoDataService.findByUrl(request.getURI().getPath());
if(!CollectionUtils.isEmpty(list)){
return JSON.parseObject(list.get(0).getContent(), body.getClass());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return body;
}
}
這裡我判斷也比較簡單,為不影響其他正常使用者使用
先判斷目前使用者的機構是否指定的機構id,在判斷有沒配置對應的url
其中DemoDataEntity 裡的字段也比較簡單,如下
@Column(length = 256)
public String title;
@Column(length = 250)
public String url;
@Lob
public String content;
我們根據請求位址,找到對應的資料,然後直接轉成對象傳回即可
轉載自:http://www.5180it.com/bbs/admin/1/117237.html