手记

工具集核心教程 | 第五篇: 利用Velocity模板引擎生成模板代码

前言

不知道大家有没有这样的感觉,在平时开发中,经常有很多daoservice类中存着很多重复的代码,Velocity提供了模板生成工具,今天我教大家怎么和这些大量的重复代码说再见。

参考项目:https://github.com/bigbeef/cppba-codeTemplate
个人博客:http://www.zhangbox.cn

注意

大家可以写适合自己的模板,这里为了演示,就直接拿cppba-web的模板来示范,至于velocity的语法大家可以查看这篇文章:
工具集核心教程 | 第四篇: Velocity模板引擎入门到大神

maven配置
 <!-- velocity -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
创建模板文件

首先看下目录结构:

这里演示我就只贴出ServiceImplTemplate.java,需要其他模板代码可以到我github里面下载

#set ($domain = $!domainName.substring(0,1).toLowerCase()+$!domainName.substring(1))
package $!{packageName}.service.impl;

import $!{packageName}.core.bean.PageEntity;
import $!{packageName}.dao.$!{domainName}Dao;
import $!{packageName}.dto.$!{domainName}Dto;
import $!{packageName}.dto.BaseDto;
import $!{packageName}.entity.$!{domainName};
import $!{packageName}.service.$!{domainName}Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 开发者
 * nickName:星缘
 * email:1342541819@qq.com
 * github:https://github.com/bigbeef
 * velocity模板生成 cppba-codeTemplate
 */
@Service
@Transactional
public class $!{domainName}ServiceImpl implements $!{domainName}Service{
    @Resource
    private $!{domainName}Dao $!{domain}Dao;

    @Override
    public void save($!{domainName} $!{domain}) {
        $!{domain}Dao.save($!{domain});
    }

    @Override
    public void delete($!{domainName} $!{domain}) {
        $!{domain}Dao.delete($!{domain});
    }

    @Override
    public void update($!{domainName} $!{domain}) {
        $!{domain}Dao.update($!{domain});
    }

    @Override
    public $!{domainName} findById(int id) {
        return ($!{domainName}) $!{domain}Dao.get($!{domainName}.class, id);
    }

    @Override
    public PageEntity<$!{domainName}> query(BaseDto baseDto) {
        String hql = " select distinct $!{domain} from $!{domainName} $!{domain} where 1=1 ";
        Map params = new HashMap<String,Object>();

        $!{domainName}Dto $!{domain}Dto = ($!{domainName}Dto)baseDto;
        $!{domainName} $!{domain} = $!{domain}Dto.get$!{domainName}();
        int page = $!{domain}Dto.getPage();
        int pageSize = $!{domain}Dto.getPageSize();

        List list = $!{domain}Dao.query(hql,params,page,pageSize);
        long count = $!{domain}Dao.count(hql,params);
        PageEntity<$!{domainName}> pe = new PageEntity<$!{domainName}>();
        pe.setCount(count);
        pe.setList(list);
        return pe;
    }
}
模板生成

接下来是生成模板的主函数:

package com.cppba.core;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 开发者
 * nickName:星缘
 * email:1342541819@qq.com
 * github:https://github.com/bigbeef
 */

public class Main {

    static String domainName = "Articles"; //类名
    static String packageName = "com.cppba";//类包

    static String templateDir = "\\src\\main\\webapp\\template\\";
    static String sourcePath = System.getProperty("user.dir")+templateDir;
    static String resultDir = "\\out";
    static String targetPath = System.getProperty("user.dir")
            + resultDir + "\\"
            + packageName.replace(".", "\\");

    public static void main(String []args) throws Exception{

        Map<String,Object> map = new HashMap();
        map.put("DaoTemplate.java","dao/" + domainName + "Dao.java");
        map.put("ServiceTemplate.java","service/" + domainName + "Service.java");
        map.put("ServiceImplTemplate.java","service/impl/" + domainName + "ServiceImpl.java");
        map.put("DtoTemplate.java","dto/" + domainName + "Dto.java");

        for(String templateFile:map.keySet()){
            String targetFile = (String) map.get(templateFile);
            Properties pro = new Properties();
            pro.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, sourcePath);
            VelocityEngine ve = new VelocityEngine(pro);

            VelocityContext context = new VelocityContext();
            context.put("domainName",domainName);
            context.put("packageName",packageName);

            Template t = ve.getTemplate(templateFile, "UTF-8");

            File file = new File(targetPath, targetFile);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            if (!file.exists())
                file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outStream,
                    "UTF-8");
            BufferedWriter sw = new BufferedWriter(writer);
            t.merge(context, sw);
            sw.flush();
            sw.close();
            outStream.close();
            System.out.println("成功生成Java文件:"
                    + (targetPath + targetFile).replaceAll("/", "\\\\"));
        }
    }
}
生成java文件

我们可以修改domainNamepackageName来修改我们的包名和类名,我们运行下看:

我们看到生成成功,我们打开ArticlesServiceImpl.java看下:

package com.cppba.service.impl;

import com.cppba.core.bean.PageEntity;
import com.cppba.dao.ArticlesDao;
import com.cppba.dto.ArticlesDto;
import com.cppba.dto.BaseDto;
import com.cppba.entity.Articles;
import com.cppba.service.ArticlesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 开发者
 * nickName:星缘
 * email:1342541819@qq.com
 * github:https://github.com/bigbeef
 * velocity模板生成 cppba-codeTemplate
 */
@Service
@Transactional
public class ArticlesServiceImpl implements ArticlesService{
    @Resource
    private ArticlesDao articlesDao;

    @Override
    public void save(Articles articles) {
        articlesDao.save(articles);
    }

    @Override
    public void delete(Articles articles) {
        articlesDao.delete(articles);
    }

    @Override
    public void update(Articles articles) {
        articlesDao.update(articles);
    }

    @Override
    public Articles findById(int id) {
        return (Articles) articlesDao.get(Articles.class, id);
    }

    @Override
    public PageEntity<Articles> query(BaseDto baseDto) {
        String hql = " select distinct articles from Articles articles where 1=1 ";
        Map params = new HashMap<String,Object>();

        ArticlesDto articlesDto = (ArticlesDto)baseDto;
        Articles articles = articlesDto.getArticles();
        int page = articlesDto.getPage();
        int pageSize = articlesDto.getPageSize();

        List list = articlesDao.query(hql,params,page,pageSize);
        long count = articlesDao.count(hql,params);
        PageEntity<Articles> pe = new PageEntity<Articles>();
        pe.setCount(count);
        pe.setList(list);
        return pe;
    }
}

生成成功,我们拷贝到cppba-web中可完美运行!

写在最后

欢迎关注喜欢、和点赞后续将推出更多的工具集教程,敬请期待。

1人推荐
随时随地看视频
慕课网APP