如何用freemark根据生成controller和service层

生成各种文件的原理都一样,只要你有模板,都可以生成,下面以一个文件来讲解,其他通用

1.添加maven

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2. 添加如下代码:

        Configuration cfg = new Configuration();
         cfg.setDefaultEncoding("utf-8");
         Template template = null;
         //加载模板的路径
         cfg.setDirectoryForTemplateLoading(new File(SecurityUtilities.getSystemProperty("user.dir")+File.separator+"src/main/resources/templates"));
         //模板名称获取
         template = cfg.getTemplate("Request2.ftl");

         //模板里的参数
         Map<String, Object> map = new HashMap<>();
         map.put("description","dddd");
         map.put("paramsGenerator","kkkkkk");
         map.put("dataType","666ddd");
         map.put("description","dddd");
         map.put("paramster","dduu");
         map.put("fieldName","ddkk");


        StringWriter result = new StringWriter(); //接收模板和参数渲染后的结果
        template.process(map, result);


        //将结果输出到指定的的路径
        OutputStreamWriter oWriter = new OutputStreamWriter(new FileOutputStream("D:\\data\\b.java"), "utf-8");
        BufferedWriter bufferedWriter = new BufferedWriter(oWriter);
        bufferedWriter.write(result.toString());
        bufferedWriter.close();
        oWriter.close();

 

模板:

 

 内容:

  
/**
* ${description}
*/
@ApiModelProperty(value = "${description}")
private ${paramsGenerator};

public ${dataType} get${fieldName}() {
return ${paramster};
}
最终输出结果:

 

 

 所以,只要将模板换成一个controller模板,生成的路径改成某个具体的包,就可以生成你要的controller类了

 










posted @ 2023-02-25 16:15  yangxiaohui227  阅读(78)  评论(0编辑  收藏  举报