首页>>后端>>Spring->ApplicationContextAware接口的实战应用

ApplicationContextAware接口的实战应用

时间:2023-11-29 本站 点击:0

需求

系统要求导入报文数据,通过excel的形式,将数据导入系统,报文分为三种报文。

分析

报文分为3种,且报文的格式都是excel,报文可以作为一个抽象,并使用模板方法模式进行导入

实践

新建抽象类IExcelOutYard

publicinterfaceIExcelOutYard{StringmessageType();voidloadExcel(Exchangeexchange,StringfileName,StringcamelFileParent);}

新建抽象类ExcelOutYardAbstract实现IExcelOutYard````@Servicepublic abstract class ExcelOutYardAbstract implements IExcelOutYard {

privatestaticLoggerlogger=LogManager.getCurrentClassLogger();@OverridepublicvoidloadExcel(Exchangeexchange,StringfileName,StringcamelFileParent){Objectbody=exchange.getIn().getBody();GenericFile<File>genericFile=(GenericFile<File>)body;Filefile=genericFile.getFile();this.analysis(file,fileName,camelFileParent);}privatevoidanalysis(Filefile,StringfileName,StringcamelFileParent){Workbookworkbook=getWorkbook(file);Sheetsheet=workbook.getSheetAt(0);Set<String>messages=Sets.newConcurrentHashSet();//1.校验数据validateMessage(sheet,messages,fileName);if(ObjectUtils.isNotEmpty(messages)){logger.error("校验不通过,原因[{}]",Joiner.on(";").join(messages));}//2组装对象List<Booking>bookings=contrustData(sheet,fileName,camelFileParent);//3插入数据saveAndUpdateData(bookings);}publicList<Booking>contrustData(Sheetsheet,StringfileName,StringcamelFileParent){returnnull;}publicvoidsaveAndUpdateData(List<Booking>bookings){}publicvoidvalidateMessage(Sheetsheet,Set<String>messages,StringfileName){}privateWorkbookgetWorkbook(Filefile){-----}}

新建ExcelOutYardAccessGate,ExcelOutYardEmpty,ExcelOutYardSo继承抽象类ExcelOutYardAbstract

@ServicepublicclassExcelOutYardSoextendsExcelOutYardAbstract{@OverridepublicStringmessageType(){returnExcelOutYardEnum.OUT_YARD_SO.name();}

新建ExcelOutYardManager 实现ApplicationContextAware接口

publicclassExcelOutYardManagerimplementsApplicationContextAware{Map<String,IExcelOutYard>excelOutYardMap;privateMap<String,IExcelOutYard>getExcelOutYard(){if(excelOutYardMap==null){excelOutYardMap=newHashMap<String,IExcelOutYard>();}returnexcelOutYardMap;}publicIExcelOutYardgetImpleService(StringmessageType){returnexcelOutYardMap.get(messageType);}@OverridepublicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{Map<String,IExcelOutYard>beansOfType=applicationContext.getBeansOfType(IExcelOutYard.class);this.getExcelOutYard();for(IExcelOutYardiExcelOutYard:beansOfType.values()){excelOutYardMap.put(iExcelOutYard.messageType(),iExcelOutYard);}}}

5.调用

StringmessageType=(String)exchange.getProperty("messageType");excelOutYardManager.getImpleService(messageType).loadExcel(exchange,fileName,camelFileParent);

结语

ApplicationContextAware接口在我前面的文章中,有所介绍,实现ApplicationContextAware接口后我们可以获得Bean容器中的所有bean,然后我们通过抽象类和他的实现,进行类型的映射,最终调用的时候,只需要传入类型码就可以了,从而实现了一个符合单一职责和开闭原则的设计。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/Spring/293.html