最近寫一個小電商項目的時候碰到一個整單/單件(退貨)以及單件換貨共用的一個接口
本來打算直接傳json字符串作為參數的
(List)JSONArray.toCollection(JSONArray.fromObject(json)
后邊發現利用框架進行簡單粗暴的集合更方便
於是參數直接寫成:
@RequestBody List<TClaimOnline> theList //TClaimOnline為封裝商品參數的單件商品對象
又發現對象中用來區別退貨和換貨的是對象的一個屬性,於是提取出來應該是最好的
於是乎在架構師的指導下
寫了一個靜態內部類
@RestController @RequestMapping(APIUrls.API_CUSTOMERSERVICE_URI) public class ReturnExchangeController { @Autowired private ReturnExchangeService returnExchangeService; @Autowired private ShopStockService shopStockService; @Autowired private TokenManager tokenManager; public static class ItemReturn { private String retExchYn; private List<TClaimOnline> theList; public String getRetExchYn() { return retExchYn; } public void setRetExchYn(String retExchYn) { this.retExchYn = retExchYn; } public List<TClaimOnline> getTheList() { return theList; } public void setTheList(List<TClaimOnline> theList) { this.theList = theList; } } ......
方法及參數寫成:
/** * 退換貨申請 * * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = APIUrls.API_FCUSTOMERSERVICE_ITEM_RETURN_APPLICATION_URI, method = RequestMethod.POST) public ResponseEntity<?> itemReturnApplication(@RequestBody ItemReturn itemReturn, HttpServletRequest request, HttpServletResponse response) throws Exception {
很好的解決了提取共性封裝數據的問題
在集合便利賦值的時候 還使用了點裝B的 Java8新寫法 :
itemReturn.getTheList().forEach(t -> {
t.setRetExchYn(itemReturn.getRetExchYn());
t.setCustNo(custNo);
t.setcCode(cCode);
});
感覺高大上了很多