Velocity 模板文件生成,基本使用

注意路径替换
Velocity 模板文件生成,基本使用_第1张图片

在模板文件中,可以通过 $name 或 ${name} 来使用定义的变量
区别:如果存在 $name 和 $names,模板文件无法识别 $names,建议使用 ${names}
${person.name} 等价于 ${person.getName()}

package zhang;

public class ${tableName}Service {
    public void get${tableName}Name(String id) {
        System.out.println("${tableName}Service.get${tableName}Name");
    }
}
<dependencies>
  <dependency>
    <groupId>org.apache.velocitygroupId>
    <artifactId>velocityartifactId>
    <version>1.7version>
  dependency>
dependencies>
public class VelocityDemo {
    public static final Path BASE_PATH = Paths.get("src/main/java/zhang").toAbsolutePath();
    public static final VelocityEngine VELOCITY_ENGINE = getInitializedVelocityEngine();


    public static void main(String[] args) throws IOException {
        String[] allServiceNames = {"User", "Order", "Goods"};
        for (String serviceName : allServiceNames) {
            Path savePath = Paths.get(String.valueOf(BASE_PATH), serviceName + "Service.java");
            File createFilePath = new File(savePath.toUri());

            // 读取 vm 模板文件,并给其内部的变量进行赋值,之后返回对应字符串内容
            StringWriter assignedValueTemplate = getAssignedValueTemplate(serviceName);
            System.out.println("\n" + assignedValueTemplate);

            // 将文件写入新创建的文件中
            writeTemplateToNewFile(createFilePath, assignedValueTemplate);
        }
    }

    private static void writeTemplateToNewFile(File createFilePath, StringWriter assignedValueTemplate) throws IOException {
        FileWriter fileWriter = new FileWriter(createFilePath);
        fileWriter.append(assignedValueTemplate.toString());
        fileWriter.flush();
        fileWriter.close();
    }

    /**
     * 根据 serviceName,获取已赋值的模板
     */
    private static StringWriter getAssignedValueTemplate(String serviceName) {
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tableName", serviceName);
        // 读取 vm 模板文件,并给其内部的变量进行赋值
        Template template = VELOCITY_ENGINE.getTemplate("/demo.vm");
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);

        return stringWriter;
    }

    /**
     * 读取 vm 模板文件,并给其内部的变量进行赋值,之后返回对应字符串内容
     */
    private static VelocityEngine getInitializedVelocityEngine() {
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        velocityEngine.init();
        return velocityEngine;
    }
}

你可能感兴趣的:(Java,java,开发语言)