java善假于物(二):利用velocity生成模板代码

前言

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

参考项目:https://github.com/bigbeef/cppba-codeTemplate
开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com

注意

大家可以写适合自己的模板,这里为了演示,就直接拿cppba-web的模板来示范,至于velocity的语法大家可以找找度娘

maven配置

1
2
3
4
5
6
 <!-- velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

创建模板文件

首先看下目录结构:

https://github.com/bigbeef/cppba-codeTemplate

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#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:245655812@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;
}
}

模板生成

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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:245655812@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文件

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

https://github.com/bigbeef/cppba-codeTemplate

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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:245655812@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中可完美运行!