代码生成器的原理
•(1)编写一个模板,比如要生成XXXService.java,service里面所有代码讲模块部分全部用占位符/变量名代替。比如MenuService改成${modelClass}Service
•(2)使用模板引擎,向模板中传递需要的占位符数据,比如${modelClass},这次要生成Menu,就传Menu,下次要建good,就传Good,就可以生成出来不同的模块,但代码只写了模板里面的这一遍
•(3)通过模板引擎,将替换好的占位符的模板输出为具体的MenuService.java、MenuController.java甚至是menu.jsp
•开发过程
•引入jar包。
•新建类com.zq.code.CodeBuilder,要有main方法,需要单独运行生成代码文件。不走spring框架;
•编写模板引擎调用代码
package com.rb.code;
import java.io.PrintWriter;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
public class CodeBuilder {
public static void main(String[] args) {
//先new一下他的模版引擎
VelocityEngine ve = new VelocityEngine();
//设置模板和输出的代码文件的编码方式
Properties p = new Properties();
p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
ve.init(p);//引擎初始化
//引入一个模板,通过模板路径
Template serviceVm = ve.getTemplate("/WebContent/WEB-INF/vm/service.vm");
//定义占位符变量, 给个值
String modelClass = "Menu";
String modelName = "menu";
//生成的代码放置的目录==项目目录
String rootPath = "F:/校企大三下/shop1";
//变量放到上下文对象里
VelocityContext ctx = new VelocityContext();
ctx.put("modelClass", modelClass);
ctx.put("modelName", modelName);
//将占位符数据和模板合并,输出代码文件
merge(serviceVm,ctx,rootPath + "/src/com/rb/service/" + modelClass + "Service.java");
}
private static void merge(Template template,VelocityContext ctx,String path){
PrintWriter writer = null;
try {
writer = new PrintWriter(path);
//合并数据和模板,输出文件
template.merge(ctx, writer);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
writer.close();
}
}
}
写service.vm模板
package com.rb.service;
import java.util.List;
import com.github.pagehelper.PageInfo;
import com.rb.model.${modelClass};
public interface ${modelClass}Service {
/**
* 带有分页的列表查询
* @param pageNum
* @param pageSize
* @param ${modelClass}
* @return
*/
public PageInfo<${modelClass}> list(Integer pageNum,Integer pageSize,${modelClass} ${modelName});
/**
* 没有分页的列表查询
* @param pageNum
* @param pageSize
* @param ${modelClass}
* @return
*/
public List<${modelClass}> list(${modelClass} ${modelName});
public void create(${modelClass} ${modelName});
public void update(${modelClass} ${modelName});
public void delete(Integer id);
public ${modelClass} findById(Integer id);
}