使用springboot,整合velocity模板,将数据库中的字典表生成java的枚举代码,
实现controller发送get,然后生成java代码文件并将文件压缩至zip压缩包,前端浏览器访问该地址直接下载zip压缩包
1:引入maven
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
2:创建controller
@RestController
@RequestMapping("/gen")
public class GenController {
@Autowired
GenService genService;
@GetMapping("/dict.gen")
public void batchGenCode(HttpServletResponse response, @RequestParam List<String> req) throws IOException {
byte[] data = genService.dictGen(req);
genCode(response, data);
}
/**
* 生成zip文件
*/
private void genCode(HttpServletResponse response, byte[] data) throws IOException {
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}
}
3:逻辑代码
@Component
public class GenService {
@Resource
SysDictTypeMapper dictTypeMapper;
public byte[] dictGen(List<String> req) {
List<DictRes> dictRes = dictTypeMapper.selectDict(req);
List<VelocityContext> velocityContexts = new ArrayList<>();
for (DictRes dictRe : dictRes) {
VelocityContext velocityContext = new VelocityContext();
boolean add = true;
if (velocityContexts.size() > 0 && velocityContexts.stream().anyMatch(v -> v.get("dictId").toString().equals(dictRe.getDictId()))) {
velocityContext = velocityContexts.stream().filter(v -> v.get("dictId").toString().equals(dictRe.getDictId())).findFirst().get();
add = false;
}
String fileName = toCamelCase(dictRe.getDictType());
velocityContext.put("fileName", fileName + ".java");
velocityContext.put("class", fileName);
velocityContext.put("desc", dictRe.getDictName());
velocityContext.put("dictId", dictRe.getDictId());
List<DictRes> dicts = new ArrayList<>();
if (velocityContext.containsKey("dicts")) {
dicts = JSON.parseArray(JSON.toJSONString(velocityContext.get("dicts")), DictRes.class);
}
dicts.add(dictRe);
velocityContext.put("dicts", dicts);
if (add) {
velocityContexts.add(velocityContext);
}
}
return downloadCode("vm/dict.java.vm", velocityContexts);
}
public byte[] downloadCode(String path, List<VelocityContext> velocityContexts) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (VelocityContext velocityContext : velocityContexts) {
if (!velocityContext.containsKey("fileName")) {
throw new RuntimeException("VelocityContext中必须指定fileName");
}
generatorCode(path, zip, velocityContext);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
private void generatorCode(String path, ZipOutputStream zip, VelocityContext velocityContext) {
VelocityInitializer.initVelocity();
// 获取模板文件
Template template = Velocity.getTemplate(path);
// 输出渲染后的结果
StringWriter stringWriter = new StringWriter();
template.merge(velocityContext, stringWriter);
// 添加到zip
try {
zip.putNextEntry(new ZipEntry(velocityContext.get("fileName").toString()));
IOUtils.write(stringWriter.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(stringWriter);
zip.flush();
zip.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 下划线
*/
private static final char SEPARATOR = '_';
/**
* 驼峰式命名法
* 例如:user_name->userName
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i == 0) {
sb.append(Character.toUpperCase(c));
continue;
}
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
}
4:用到的实体类
@Data
public class DictRes {
@ApiModelProperty("主键")
private String dictId;
@ApiModelProperty("字典名称")
private String dictName;
@ApiModelProperty("字典类型")
private String dictType;
@ApiModelProperty("字典枚举名称")
private String dictLabel;
@ApiModelProperty("字典枚举代码")
private String dictValue;
}
5:用到的velocity模板工厂类
public class VelocityInitializer
{
/**
* 初始化vm方法
*/
public static void initVelocity()
{
Properties p = new Properties();
try
{
// 加载classpath目录下的vm文件
p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 定义字符集
p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
// 初始化Velocity引擎,指定配置Properties
Velocity.init(p);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
6: 用到的vm模板文件,需要将文件命名 dict.java.vm 并放到项目的 resource/vm 目录下
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;
import lombok.Setter;
//${desc}
public enum ${class} {
#foreach($key in ${dicts})
${key.dictValue}("${key.dictValue}", "${key.dictLabel}"),
#end
;
@JsonValue
@Getter
@Setter
private String code;
@Getter
@Setter
private String info;
${class}(String code, String info) {
this.code = code;
this.info = info;
}
@JsonCreator
public static ${class} getEnumByValue(String code) {
for (${class} bt : values()) {
if (bt.getCode().equals(code)) {
return bt;
}
}
return null;
}
public static String getValue(String info) {
for (${class} s : ${class}.values()) {
if (s.getInfo().equals(info)) {
return s.getCode();
}
}
return "";
}
public static String getName(String code) {
for (${class} s : ${class}.values()) {
if (s.getCode().equals(code)) return s.getInfo();
}
return "";
}
}