资讯专栏INFORMATION COLUMN

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

leon / 1095人阅读

摘要:欢迎关注我的微信公众号获取更多更全的学习资源,视频资料,技术干货公众号回复学习,拉你进程序员技术讨论群,干货资源第一时间分享。公众号回复全栈,领取前端,,产品经理,微信小程序,等资源合集大放送。公众号回复面试,领取面试实战学习资源。

前言

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

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

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

maven配置
 

    org.apache.velocity
    velocity
    1.7

创建模板文件

首先看下目录结构:

这里演示我就只贴出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();

        $!{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 = "srcmainwebapp	emplate";
    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 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 query(BaseDto baseDto) {
        String hql = " select distinct articles from Articles articles where 1=1 ";
        Map params = new HashMap();

        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 pe = new PageEntity();
        pe.setCount(count);
        pe.setList(list);
        return pe;
    }
}

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

写在最后

欢迎关注喜欢、和点赞后续将推出更多的工具集教程,敬请期待。
欢迎关注我的微信公众号获取更多更全的学习资源,视频资料,技术干货!

公众号回复“学习”,拉你进程序员技术讨论群干货资源第一时间分享。

公众号回复“视频”,领取800GJava视频学习资源。

公众号回复“全栈”,领取1T前端Java产品经理微信小程序Python等资源合集大放送。





公众号回复“慕课”,领取1T慕课实战学习资源。








公众号回复“实战”,领取750G项目实战学习资源。

公众号回复“面试”,领取8G面试实战学习资源。



文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77590.html

相关文章

  • 具集核心教程 | 第四篇: Velocity模板引擎入门到进阶

    摘要:是一个基于的模板引擎。模板中未被定义的变量将被认为是一个字符串。公众号回复全栈,领取前端,,产品经理,微信小程序,等资源合集大放送。公众号回复面试,领取面试实战学习资源。 Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。 当Velocity应用于web...

    leon 评论0 收藏0
  • 动手搭建后端框架-Velocity模板引擎的应用

    摘要:目录建造者模式应用。其实不用也可以,因为不是很复杂,只是为了复习一下所学过的设计模式知识目录工厂模式应用。 为了提高开发效率,通常会想办法把一些模式固定的重复性的劳动抽取出来,以后再使用的时候,拿来主义就可以了。这样既可以提高开发效率,又降低了出错的风险。 这一思想在我们的日常工作中可以说随处可见,我们完成一项复杂的工程,并不需要面面俱到什么都自己写,我们完全可以利用第三方的jar包让...

    villainhr 评论0 收藏0
  • 具集核心教程 | 第三篇: Thymeleaf模板引擎入门到进阶

    摘要:介绍简单说,是一个跟类似的模板引擎,它可以完全替代。不包含标记删除但删除其所有的孩子。公众号回复全栈,领取前端,,产品经理,微信小程序,等资源合集大放送。公众号回复面试,领取面试实战学习资源。 thymeleaf介绍 简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP。相较与其他的模板引擎,它有如下三个极吸引人的特点:...

    abson 评论0 收藏0

发表评论

0条评论

leon

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<