【記錄】velocity模板引擎,讓你放開雙手,一鍵生成程式碼
阿新 • • 發佈:2020-07-18
最近專案中需要編寫幾十個介面,包括欄位查詢,匯出,id查詢單個,如果單純CV工作量很大,還有可能出現錯誤。
無意間發現velocity模板引擎,只需要編寫通用模板,利用java反射技術,可以實現一鍵批量生成java檔案
包括Controller、Service、ServiceImpl、Mapper、BO、DTO 檔案,大大提高效率。學習成本很低,牆裂推薦。
首先引入依賴
<!-- 生成程式碼模板工具--> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency>
編寫模板,以Mapper模板為例
package ${packageName} import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import ${importDtoName} /** *<p> * ${tableComment} Mapper 介面 * </p> * * @author ${author} * @date ${date} */ @Mapper public interface ${className}Mapper extends BaseMapper<${className}DTO> { }
模板中動態變數對應實體類 ,名字要一 一對應
import lombok.Data; /** * @Description 父模板引數 */ @Data public class ParentTemplateParam { private String author; private String date; private String tableName; private String tableComment; private String className; private String classNameObj; // 生成的檔名 private String fileName; private String importServiceName; private String importBoName; private String importDtoName; private String importMapperName; private String packageName; private String requestMappingUrl; private String replaceContent; // 所屬模組名稱 private String module; }
利用反射技術,動態賦值,以下只貼上部分程式碼,供大家參考
import org.springframework.cglib.beans.BeanMap; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import com.xxx.xxxx.ParentTemplateParam; /** * Mapper模板路徑 */ private static final String MAPPER_TEMPLATE_PATH = "/template/MapperTemplate"; Map<String, Object> param = new HashMap<>(); // 模板引數 ParentTemplateParam parentTemplateObj = getParentTemplateObj(clazz, commonTemplateParam, tableComment); // Obj轉map param = ObjectUtils.isEmpty(parentTemplateObj) ? new HashMap<>() : BeanMap.create(parentTemplateObj); // 替換模板中關鍵字 String resultTemplate = getResultTemplate(param, templatePath);
Velocity引擎替換關鍵字
/** * 獲取替換後的字串 * * @param param 引數 * @return java.lang.String 返回引數說明 * @exception/throws */ public static String getResultTemplate(Map<String, Object> param, String filePath) { //1.將模版以檔案的形式讀入 //獲取檔案地址 File path = new File(filePath); //獲取檔案絕對路徑 Path absolutePath = Paths.get(path.toString()); //2.將讀入的檔案轉為string 字串 //讀取其內容 String template = ""; try { template = new String(Files.readAllBytes(absolutePath), "UTF8"); } catch (IOException e) { e.printStackTrace(); } String resultTemplate = ""; if (!StringUtils.isEmpty(template)) { //建立模版引起上下文 並傳入要替換的引數 VelocityContext vc = new VelocityContext(param); //建立StringWriter物件 其內部是對StringBuffer進行的操作 StringWriter writer = new StringWriter(); //模版引起開始替換模版內容 Velocity.evaluate(vc, writer, "", template); //替換之後的字串 resultTemplate = writer.getBuffer().toString(); } return resultTemplate; }
匯出檔案
// 匯出檔案 ExportFileUtil.writeData2File(exportPath, resultTemplate, fileName); /** * 寫入檔案 * @param content 引數說明 * @param fileName 引數說明 * @return boolean 返回引數說明 * @exception/throws */ public static boolean writeData2File(String exportPath,String content, String fileName) { boolean flag = false; BufferedWriter out = null; try { if (!ObjectUtils.isEmpty(content) && StringUtils.isNotEmpty(fileName)) { fileName = fileName + ".java"; File pathFile = new File(exportPath); if (!pathFile.exists()) { pathFile.mkdirs(); } String relFilePath = exportPath + File.separator + fileName; File file = new File(relFilePath); if (!file.exists()) { file.createNewFile(); } out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); out.write(content); out.newLine(); flag = true; } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } return flag; } }
最後執行可以看到生成的mapper.java檔案,直接拷貝貼上到專案裡。
是不是很方便,節省了很多時間,下次遇到直接生成就好。
更多關於Velocity的用法請自行百度