【记录】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的用法请自行百度

原文地址:https://www.cnblogs.com/wbl001/p/13334858.html