转载自: http://www.513school.com/bbs/admin/1/111643.html
生成代码在开发过程可以节约开发时间,这里介绍beetl生成代码方式
在此就不多说beetl的好处,直接上代码
首先pom.xml引入beetle包如下:
主类
/**
* 运行该主函数即可生成代码
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 模板路径
ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/codetemplate/background/");
Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
// 生成代码
//根据类名删除生成的代码
generateCode(gt, TemplateType.BaseController, "CodeTemplateSubEntity", "代码生成模板子表", "liusheng", "bs.code");
}
public enum TemplateType{
BaseController("BaseEntity", "BaseController", "BaseServiceImpl", "BaseRepository"),
TreeController("TreeEntity", "TreeController", "TreeServiceImpl", "BaseRepository"),
SubController("SubEntity", "BaseController", "BaseServiceImpl", "SubRepository"),
SuperController("SuperEntity", "SuperController", "SuperServiceImpl", "BaseRepository"),
Workflow("AuditEntity", "BaseProcessController", "BaseWorkflowService", "BaseRepository");
/**
* 继承的entity父类
*/
private String extendsEntity;
/**
* 继承的controller父类
*/
private String extendsController;
/**
* 继承的service父类
*/
private String extendsServiceImpl;
/**
* 继承的dao父类
*/
private String extendsRepository;
private Class> subEntity;
private Class> subDao;
private TemplateType(String extendsEntity, String extendsController, String extendsServiceImpl, String extendsRepository) {
this.extendsEntity = extendsEntity;
this.extendsController = extendsController;
this.extendsServiceImpl = extendsServiceImpl;
this.extendsRepository = extendsRepository;
}
public String getExtendsController() {
return extendsController;
}
public String getExtendsServiceImpl() {
return extendsServiceImpl;
}
public String getExtendsEntity() {
return extendsEntity;
}
public String getExtendsRepository() {
return extendsRepository;
}
public Class> getSubEntity() {
return subEntity;
}
public void setSubEntity(Class> subEntity) {
this.subEntity = subEntity;
}
public void setSubDao(Class> subDao) {
this.subDao = subDao;
}
public Class> getSubDao() {
return subDao;
}
}
/**
* 生成代码
*
* @param gt
* @param author
* @param description
* @param className
* @throws IOException
*/
private static void generateCode(GroupTemplate gt, TemplateType templateType, String className, String description,
String author, String modules) throws IOException {
Template entityTemplate = gt.getTemplate("entity.btl");
Template daoTemplate = gt.getTemplate("dao.btl");
Template serviceTemplate = gt.getTemplate("service.btl");
Template controllerTemplate = gt.getTemplate("controller.btl");
String entityPackage = packages + "domain" +
modules.substring(modules.lastIndexOf("."), modules.length());// + ".entity";
String daoPackage = packages + modules;// + ".mapper";
String servicePackage = packages + modules;// + ".service";
String serviceImplPackage = packages + modules;// + ".serviceimpl";
String controllerPackage = packages + modules;// + ".controller";
YyCodeEntity entity = new YyCodeEntity();
entity.setEntityPackage(entityPackage);
entity.setDaoPackage(daoPackage);
entity.setServicePackage(servicePackage);
entity.setServiceImplPackage(serviceImplPackage);
entity.setControllerPackage(controllerPackage);
entity.setAuthor(author);
entity.setClassName(className);
entity.setTableName(tablePre + camel2Underline(className).replace("_entity", ""));
entity.setClassFileName(replaceEntityName(className));
entity.setClassNameLowerCase(firstCharChange(replaceEntityName(className), false));
entity.setDescription(description);
entity.setPrimaryKeyType(primaryKeyType);
entity.setExtendsEntity(templateType.getExtendsEntity());
entity.setExtendsController(templateType.getExtendsController());
entity.setExtendsServiceImpl(templateType.getExtendsServiceImpl());
entity.setExtendsRepository(templateType.getExtendsRepository());
if(templateType.equals(TemplateType.SuperController)){
entity.setSubEntity(templateType.getSubEntity().getName());
// entity.setSubServcie(", " + templateType.getSubEntity().getName());
entity.setSubDao(templateType.getSubDao().getName());
}else{
entity.setSubEntity("");
// entity.setSubServcie("");
entity.setSubDao("");
}
OutputStream out = null;
//生成实体类代码
entityTemplate.binding("entity", entity);
String entityResult = entityTemplate.render();
System.out.println(entityResult);
//创建文件
String entityFileUrl = System.getProperty("user.dir") + "/src/main/java/" + dotToLine(entityPackage) + "/" + className + ".java";
File entityFile = new File(entityFileUrl);
File entityDir = entityFile.getParentFile();
if (!entityDir.exists()) {
entityDir.mkdirs();
}
if (!entityFile.exists()) {
// 若文件存在则不重新生成
entityFile.createNewFile();
out = new FileOutputStream(entityFile);
entityTemplate.renderTo(out);
}
//生成dao代码
daoTemplate.binding("entity", entity);
String daoResult = daoTemplate.render();
System.out.println(daoResult);
//创建文件
String daoFileUrl = System.getProperty("user.dir") + "/src/main/java/" + dotToLine(daoPackage) + "/" + replaceEntityName(className) + "Dao.java";
File daoFile = new File(daoFileUrl);
File daoDir = daoFile.getParentFile();
if (!daoDir.exists()) {
daoDir.mkdirs();
}
if (!daoFile.exists()) {
// 若文件存在则不重新生成
daoFile.createNewFile();
out = new FileOutputStream(daoFile);
daoTemplate.renderTo(out);
}
//生成service代码
serviceTemplate.binding("entity", entity);
String serviceResult = serviceTemplate.render();
System.out.println(serviceResult);
//创建文件
String serviceFileUrl = System.getProperty("user.dir") + "/src/main/java/" + dotToLine(servicePackage) + "/" + replaceEntityName(className) + "Service.java";
File serviceFile = new File(serviceFileUrl);
File serviceDir = serviceFile.getParentFile();
if (!serviceDir.exists()) {
serviceDir.mkdirs();
}
if (!serviceFile.exists()) {
// 若文件存在则不重新生成
serviceFile.createNewFile();
out = new FileOutputStream(serviceFile);
serviceTemplate.renderTo(out);
}
//生成controller代码
controllerTemplate.binding("entity", entity);
String controllerResult = controllerTemplate.render();
System.out.println(controllerResult);
//创建文件
String controllerFileUrl = System.getProperty("user.dir") + "/src/main/java/" + dotToLine(controllerPackage) + "/" + replaceEntityName(className) + "Controller.java";
File controllerFile = new File(controllerFileUrl);
File controllerDir = controllerFile.getParentFile();
if (!controllerDir.exists()) {
controllerDir.mkdirs();
}
if (!controllerFile.exists()) {
// 若文件存在则不重新生成
controllerFile.createNewFile();
out = new FileOutputStream(controllerFile);
controllerTemplate.renderTo(out);
}
if (out != null) {
out.close();
}
System.out.println("已完成!自行挪动代码即可");
}
controller.btl
package ${entity.controllerPackage};
import ${entity.entityPackage}.${entity.className};
import ${entity.servicePackage}.${entity.ClassFileName}Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yy.frame.controller.${entity.extendsController};
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author ${entity.author}
*/
@RestController
@RequestMapping(value = "/${entity.classNameLowerCase}")
public class ${entity.ClassFileName}Controller extends ${entity.extendsController}<${entity.className}>{
Logger logger = LoggerFactory.getLogger(${entity.ClassFileName}Controller.class);
@SuppressWarnings("unused")
@Autowired
private ${entity.ClassFileName}Service ${entity.classNameLowerCase}Service;
}
service.btl
package ${entity.servicePackage};
import ${entity.entityPackage}.${entity.className};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yy.frame.dao.BaseRepository;
<%if(entity.subEntity != ''){%>import com.yy.frame.dao.SubRepository;<%}%>
import com.yy.frame.service.${entity.extendsServiceImpl};
/**
* ${entity.description} 业务层
* @author ${entity.author}
*/
@Service
@Transactional(readOnly = true, rollbackFor = { Exception.class })
public class ${entity.ClassFileName}Service extends ${entity.extendsServiceImpl}<${entity.className}, String<%if(entity.subEntity != ''){%>, ${entity.subEntity}<%}%>> {
static public Logger logger = LoggerFactory.getLogger(${entity.ClassFileName}Service.class);
@Autowired
private ${entity.ClassFileName}Dao dao;
<%if(entity.subEntity != ''){%>
@Autowired
private ${entity.subDao} subDao;
<%}%>
@Override
protected BaseRepository<${entity.className}, String> getDAO() {
return dao;
}
<%if(entity.subEntity != ''){%>
@Override
protected SubRepository<${entity.subEntity}, String> getSubDAO() {
return subDao;
}
<%}%>
}
dao.btl
package ${entity.daoPackage};
import com.yy.frame.dao.${entity.extendsRepository};
import ${entity.entityPackage}.${entity.className};
/**
* ${entity.description} Dao层
* @author ${entity.author}
*/
public interface ${entity.ClassFileName}Dao extends ${entity.extendsRepository}<${entity.className}, String> {
}
entity.btl
package ${entity.entityPackage};
import javax.persistence.Entity;
import javax.persistence.Table;
import com.yy.frame.entity.${entity.extendsEntity};
import com.yy.common.annotation.MetaData;
import com.yy.common.annotation.ObjectDate;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
/**
* ${entity.description} Entity层
* @author ${entity.author}
*/
@MetaData(value = "${entity.description}")
@ObjectDate(value = "${entity.description}")
@Entity
@Table(name = "${entity.tableName}")
@DynamicInsert
@DynamicUpdate
public class ${entity.className} extends ${entity.extendsEntity}<%if(entity.subEntity != ''){%><${entity.subEntity}><%}%> {
private static final long serialVersionUID = 1L;
}
更多的beetl语法可以自己网上查询,这样就可以灵活的根据模板生成代码了