velocity代码生成器的使用

1.导入依赖

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>

2.resource资源文件中

3.codegenerator.java

package cn.fifdistrict.basic;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;

import java.io.*;
import java.util.Properties;

public class CodeGenerator {

    //代码生成路径
    private static String mapperPath;
    private static String servicePath;
    private static String serviceImplPath;
    private static String controllerPath;
    private static String queryPath;
    private static String jspPath;
    private static String jsPath;

    static{
        //加载路径
        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(CodeGenerator.class.getClassLoader().getResourceAsStream("generator.properties"),"utf-8"));
            mapperPath = properties.getProperty("gen.mapper.path");
            servicePath = properties.getProperty("gen.service.path");
            serviceImplPath = servicePath+"\\impl";
            controllerPath = properties.getProperty("gen.controller.path");
            queryPath = properties.getProperty("gen.query.path");
            jspPath = properties.getProperty("gen.jsp.path")+"\\domain";
            jsPath = properties.getProperty("gen.js.path");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //代码生成的先后顺序
    private static final String[] paths = {controllerPath,servicePath,
            serviceImplPath,mapperPath,queryPath,jspPath,jsPath};
    //模板先后顺序
    private static final String[] templates = {"DomainController.java.vm",
            "IDomainService.java.vm","DomainServiceImpl.java.vm",
            "DomainMapper.java.vm","DomainQuery.java.vm","index.jsp.vm",
            "domain.js.vm"};

    //要生成的那些实体类的相关代码
    private static final String[] domains = {"Operationlog"};

    //是否覆盖
    private static final boolean FLAG = true;

    @Test
    public void test() throws Exception{

        //模板上下文
        VelocityContext context = new VelocityContext();
        //遍历所有的domain
        for (String domain : domains) {
            //拿到domain类名的大小写
            String DomainName = domain;
            String domainName = domain.substring(0,1).toLowerCase()+
                    domain.substring(1);
            //上下文中设置替换内容
            context.put("Domain",DomainName);
            context.put("domain",domainName);
            //遍历路径,拿到模板生成目标文件
            for (int i=0;i<paths.length;i++) {

                //初始化参数
                Properties properties=new Properties();
                //设置velocity资源加载方式为class
                properties.setProperty("resource.loader", "class");
                //设置velocity资源加载方式为file时的处理类
                properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
                //实例化一个VelocityEngine对象
                VelocityEngine velocityEngine=new VelocityEngine(properties);

                String templateName = templates[i];
                //生成代码
                //生成的文件名
                String fileName = templateName.substring(0, templateName.lastIndexOf(".vm"));
                String filePath = paths[i]+"\\"+fileName;
                filePath = filePath.replaceAll("domain", domainName).
                        replaceAll("Domain", DomainName);
                File file = new File(filePath);

                System.out.println(filePath);

                //判断是否覆盖存在的文件
                if(file.exists()&&!FLAG){
                    continue;
                }

                //获取父目录
                File parentFile = file.getParentFile();
                if(!parentFile.exists()){
                    parentFile.mkdirs();
                }
                Writer writer = new FileWriter(file);
                //拿到模板,设置编码
                velocityEngine.mergeTemplate("template/"+templateName,"utf-8",context,writer);
                writer.close();

            }

        }

    }

}
--rebel.xml
<?xml version="1.0" encoding="UTF-8"?>

<!--
  This is the JRebel configuration file. It maps the running application to your IDE workspace, enabling JRebel reloading for this project.
  Refer to https://manuals.zeroturnaround.com/jrebel/standalone/config.html for more information.
-->
<application generated-by="intellij" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd">

   <classpath>
      <dir name="D:/ruanjian/code/workspace/dms-parent/basic-generator/target/classes">
      </dir>
   </classpath>

</application>

--rebel-remote.xml
<?xml version="1.0" encoding="UTF-8"?>
<rebel-remote xmlns="http://www.zeroturnaround.com/rebel/remote">
    <id>basic-generator</id>
</rebel-remote>

--generator.properties
#代码生成路径
#query生成的目录
gen.query.path=D:\\ruanjian\\code\\workspace\\dms-parent\\dms-common\\src\\main\\java\\cn\\fifdistrict\\dms\\query
#mapper生成的目录
gen.mapper.path=D:\\ruanjian\\code\\workspace\\dms-parent\\dms-mapper\\src\\main\\java\\cn\\fifdistrict\\dms\\mapper
#controller生成的目录
gen.controller.path=D:\\ruanjian\\code\\workspace\\dms-parent\\dms-web\\src\\main\\java\\cn\\fifdistrict\\dms\\web\\controller
#service生成的目录
gen.service.path=D:\\ruanjian\\code\\workspace\\dms-parent\\dms-service\\src\\main\\java\\cn\\fifdistrict\\dms\\service
#jsp生成的目录
gen.jsp.path=D:\\ruanjian\\code\\workspace\\dms-parent\\dms-web\\src\\main\\webapp\\WEB-INF\\views
#js生成的目录
gen.js.path=D:\\ruanjian\\code\\workspace\\dms-parent\\dms-web\\src\\main\\webapp\\static\\js\\model
--template
package cn.fifdistrict.dms.web.controller;

import cn.fifdistrict.dms.domain.${Domain};
import cn.fifdistrict.dms.query.${Domain}Query;
import cn.fifdistrict.dms.service.I${Domain}Service;
import cn.fifdistrict.basic.util.AjaxResult;
import cn.fifdistrict.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("/${domain}")
public class ${Domain}Controller {

    @Autowired
    private I${Domain}Service ${domain}Service;

    /**
     * 保存
     * @return
     */
    @RequestMapping(value = "save",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult save(${Domain} ${domain}){
        try {
            if(${domain}.getId()==null){
                ${domain}Service.add(${domain});
            }else{
                ${domain}Service.update(${domain});
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult("保存失败!"+e.getMessage());
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult delete(Long id){
        try {
            ${domain}Service.delete(id);
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult("删除失败!"+e.getMessage());
        }
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping(value = "/getOne",method = RequestMethod.GET)
    @ResponseBody
    public ${Domain} getOne(Long id){
        return ${domain}Service.get(id);
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    @ResponseBody
    public List<${Domain}> getAll(){
        return ${domain}Service.getAll();
    }

    /**
     * 条件分页查询
     * @param query
     * @return
     */
    @RequestMapping(value = "/query",method = RequestMethod.GET)
    @ResponseBody
    public PageList<${Domain}> query(${Domain}Query query){
        return ${domain}Service.queryPage(query);
    }
    
}

本文参考自:https://www.cnblogs.com/wgyi140724-/p/10572646.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值