您好,登錄后才能下訂單哦!
我在實際開發中遇到有一段公共的代碼,幾個方法都需要掉,但如果單獨拉出來寫一個方法的話,入參又不同,所以想到了用泛型。
比如這是一段公共代碼:
//保存訂單信息,需要多個方法調用 OrderFilterRequest orderFilterRequest = new OrderFilterRequest(); btOrderFilterRequest.setUserId("1"); btOrderFilterRequest.setStatus("0"); List<Order> orderResultList = orderService.findOrders(orderFilterRequest); Order result = null; if(CollectionUtils.isEmpty(orderResultList )){ Order order = CopierUtils.convert(request, Order.class); order.setRealName(customer.getRealName()); order.setIdcardNo(customer.getIdcardNo()); order.setOrderNo("order" + DateUtil.getYMDHMS()); order.setStatus("0"); order.setCreateTime(new Date()); order.setUpdateTime(new Date()); order.setUserId("1"); result = orderService.createOrder(Order); }else{ Order orderResult = orderResultList.get(0); CopierUtils.copy(request, orderResult); orderResult.setUpdateTime(new Date()); result = orderService.updateOrder(btOrderResult); }
將這段代碼提煉成泛型類:
@Transactional(readOnly = true) @Component public class OrderRequest<T>{ @Autowired private OrderService orderService; @Transactional public Order orderInfoSave(T request) { OrderFilterRequest orderFilterRequest = new OrderFilterRequest(); btOrderFilterRequest.setUserId("1"); btOrderFilterRequest.setStatus("0"); List<Order> orderResultList = orderService.findOrders(orderFilterRequest); Order result = null; if(CollectionUtils.isEmpty(orderResultList )){ Order order = CopierUtils.convert(request, Order.class); order.setRealName(customer.getRealName()); order.setIdcardNo(customer.getIdcardNo()); order.setOrderNo("order" + DateUtil.getYMDHMS()); order.setStatus("0"); order.setCreateTime(new Date()); order.setUpdateTime(new Date()); order.setUserId("1"); result = orderService.createOrder(Order); }else{ Order orderResult = orderResultList.get(0); CopierUtils.copy(request, orderResult); orderResult.setUpdateTime(new Date()); result = orderService.updateOrder(btOrderResult); } return result; } }
最開始我是這么調用的:
public void method1(Request1 request ) { OrderRequest<Request1> orderCreateRequest = new OrderRequest<Request1>(); Order result = OrderCreateRequest.orderInfoSave(request); } public void method2(Request2 request ) { OrderRequest<Request2> orderCreateRequest = new OrderRequest<Request2>(); Order result = OrderCreateRequest.orderInfoSave(request); }
但是OrderRequest中orderService為null。(在controller層中注入service接口,在service層中注入orderService是有值的),嘗試可很多解決辦法,最后發現,原來spring自定義的類實例化時也需要用注入的方式,不能用new,否則脫離了spring的管理。改成如下方式就可以了:
@Autowired private OrderRequest<Request1> request1; @Autowired private OrderRequest<Request2> request2; public void method1(Request1 request ) { Order result = request1.orderInfoSave(request); } public void method2(Request2 request ) { Order result = request2.orderInfoSave(request); }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。