我在实际开发中遇到有一段公共的代码,几个方法都需要掉,但如果单独拉出来写一个方法的话,入参又不同,所以想到了用泛型。
创新互联建站坚持“要么做到,要么别承诺”的工作理念,服务领域包括:做网站、成都网站制作、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的郓城网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!
比如这是一段公共代码:
//保存订单信息,需要多个方法调用 OrderFilterRequest orderFilterRequest = new OrderFilterRequest(); btOrderFilterRequest.setUserId("1"); btOrderFilterRequest.setStatus("0"); ListorderResultList = 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{ @Autowired private OrderService orderService; @Transactional public Order orderInfoSave(T request) { OrderFilterRequest orderFilterRequest = new OrderFilterRequest(); btOrderFilterRequest.setUserId("1"); btOrderFilterRequest.setStatus("0"); List 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 ) { OrderRequestorderCreateRequest = new OrderRequest (); Order result = OrderCreateRequest.orderInfoSave(request); } public void method2(Request2 request ) { OrderRequest orderCreateRequest = new OrderRequest (); Order result = OrderCreateRequest.orderInfoSave(request); }
但是OrderRequest中orderService为null。(在controller层中注入service接口,在service层中注入orderService是有值的),尝试可很多解决办法,最后发现,原来spring自定义的类实例化时也需要用注入的方式,不能用new,否则脱离了spring的管理。改成如下方式就可以了:
@Autowired private OrderRequestrequest1; @Autowired private OrderRequest request2; public void method1(Request1 request ) { Order result = request1.orderInfoSave(request); } public void method2(Request2 request ) { Order result = request2.orderInfoSave(request); }