【記錄】velocity模板引擎,讓你放開雙手,一鍵生成代碼


 

最近項目中需要編寫幾十個接口,包括字段查詢,導出,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的用法請自行百度

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM