本篇内容介绍了“Java的Freemarker类怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
一、工具类
public class FreemarkerUtil { public static void execute(String ftlNameWithPath, Map<String, Object> data, String aimFileName) throws IOException, TemplateException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);//创建Freemarker配置实例 int i = ftlNameWithPath.lastIndexOf("/") == -1 ? ftlNameWithPath.lastIndexOf("\\") : ftlNameWithPath.lastIndexOf("/"); cfg.setDirectoryForTemplateLoading(new File(ftlNameWithPath.substring(0, i + 1))); cfg.setDefaultEncoding("UTF-8"); Template t1 = cfg.getTemplate(ftlNameWithPath.substring(i + 1));//加载模板文件 Writer out = new FileWriter(new File(aimFileName)); t1.process(data, out); out.flush(); out.close(); }}
二、测试
模板文件:service.ftl
package com.resume.service;import com.baomidou.mybatisplus.extension.service.IService;import com.resume.domain.${className};import java.util.List;public interface ${className}Service extends IService<${className}> { List<${className}> listAllUsable${className}(); boolean modify${className}Status(Integer id, Integer status); boolean modify(${className} ${objName});}
测试代码:
public class GenApplication { private static String className = "Project"; private static String objName = "project"; private static String comment = "期日经验"; private static String basePath = "src/main/java/com/resume/"; public static void main(String[] args) throws IOException, TemplateException { // 生成Service接口 genService(className, objName, comment); } private static void genService(String className, String objName, String comment) throws IOException, TemplateException { String ftlNameWithPath = basePath + "utils/gen/ftl/service.ftl"; String aimFileName = basePath + "service/" + className + "Service.java"; Map<String, Object> map = new HashMap<>(); map.put("objName", objName); map.put("className", className); map.put("comment", comment); FreemarkerUtil.execute(ftlNameWithPath, map, aimFileName); }}
“Java的Freemarker类怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!