一 需求
系统要求导入报文数据,通过excel的形式,将数据导入系统,报文分为三种报文。
二 分析
报文分为3种,且报文的格式都是excel,报文可以作为一个抽象,并使用模板方法模式进行导入
三 实践
新建抽象类
IExcelOutYard
public interface IExcelOutYard { String messageType(); void loadExcel(Exchange exchange, String fileName, String camelFileParent); }
新建抽象类
ExcelOutYardAbstract
实现IExcelOutYard
@Service public abstract class ExcelOutYardAbstract implements IExcelOutYard { private static Logger logger = LogManager.getCurrentClassLogger(); @Override public void loadExcel(Exchange exchange, String fileName,String camelFileParent) { Object body = exchange.getIn().getBody(); GenericFile<File> genericFile = (GenericFile<File>) body; File file = genericFile.getFile(); this.analysis(file, fileName,camelFileParent); } private void analysis(File file, String fileName,String camelFileParent) { Workbook workbook = getWorkbook(file); Sheet sheet = 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); }
public List<Booking> contrustData(Sheet sheet, String fileName,String camelFileParent) {
return null;
}
public void saveAndUpdateData(List<Booking> bookings) {
}
public void validateMessage(Sheet sheet, Set<String> messages, String fileName) {
}
private Workbook getWorkbook(File file) {
-----
}
}
```
3. 新建`ExcelOutYardAccessGate`,`ExcelOutYardEmpty`,`ExcelOutYardSo`继承抽象类`ExcelOutYardAbstract`
```
@Service
public class ExcelOutYardSo extends ExcelOutYardAbstract {
@Override
public String messageType() {
return ExcelOutYardEnum.OUT_YARD_SO.name();
}
```
4. 新建`ExcelOutYardManager` 实现`ApplicationContextAware`接口
```
public class ExcelOutYardManager implements ApplicationContextAware {
Map<String,IExcelOutYard> excelOutYardMap;
private Map<String, IExcelOutYard> getExcelOutYard() {
if (excelOutYardMap == null) {
excelOutYardMap = new HashMap<String, IExcelOutYard>();
}
return excelOutYardMap;
}
public IExcelOutYard getImpleService(String messageType){
return excelOutYardMap.get(messageType);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, IExcelOutYard> beansOfType = applicationContext.getBeansOfType(IExcelOutYard.class);
this.getExcelOutYard();
for (IExcelOutYard iExcelOutYard:beansOfType.values()) {
excelOutYardMap.put(iExcelOutYard.messageType(),iExcelOutYard);
}
}
}
```
5.调用
String messageType = (String) exchange.getProperty("messageType");
excelOutYardManager.getImpleService(messageType).loadExcel(exchange, fileName,camelFileParent);
三 结语
ApplicationContextAware接口在我前面的文章中,有所介绍,实现ApplicationContextAware接口后我们可以获得Bean容器中的所有bean,然后我们通过抽象类和他的实现,进行类型的映射,最终调用的时候,只需要传入类型码就可以了,从而实现了一个符合单一职责和开闭原则的设计。