在Java开发的过程中,增删改查的代码总是着浪费程序员的生命和热情。使用Velocity库来生成代码是一件非常轻松的事情,而绝大多数的项目都只是将代码模板存进静态文件中,进行读取和替换操作。想要最大限度的客制化,支持多种开发语言,我们必须抛弃vm文件!
目前探索出两种方式:
第一种方式:
自定义VM模板加载器
可以在这里读取数据库
import java.io.*;
import java.nio.charset.StandardCharsets;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExtProperties;
/**
* 自定义VM模板加载器
*
* @author xurenyi
* @since 2023/12/22 16:45
*/
public class VmResourceLoader extends ResourceLoader {
@Override
public long getLastModified(Resource arg0) {
return 0;
}
@Override
public void init(ExtProperties configuration) {
}
/**
* 动态加载vm文件内容
*
* @param source
* @param encoding
*/
@Override
public Reader getResourceReader(String source, String encoding) throws ResourceNotFoundException {
String str = "-- 菜单 SQL\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 'admin', sysdate(), '', null, '${functionName}菜单');\n" +
"\n" +
"-- 按钮父菜单ID\n" +
"SELECT @parentId := LAST_INSERT_ID();\n" +
"\n" +
"-- 按钮 SQL\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}查询', @parentId, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}新增', @parentId, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}修改', @parentId, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}删除', @parentId, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}导出', @parentId, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 'admin', sysdate(), '', null, '');";
InputStream inputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
Reader reader = new InputStreamReader(inputStream);
// inputStream = new ByteArrayInputStream(reader.toString().getBytes(StandardCharsets.UTF_8));
return reader;
}
@Override
public boolean isSourceModified(Resource arg0) {
return false;
}
}
测试类
import java.io.StringWriter;
import java.util.Properties;
import com.ruoyi.common.constant.Constants;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class test {
/**
* 自定义VM资源加载器 测试
*/
public static void main(String[] args) {
// 创建引擎
VelocityEngine ve = new VelocityEngine();
Properties p = new Properties();
// 设置自定义loader的名称srl
p.put("resource.loader", "srl");
// 指定读取的class文件,注意文件的包路径
p.put("srl.resource.loader.class", "xxx.gen.tmpl.loader.VmResourceLoader");
try {
//进行初始化操作
ve.init(p);
//加载模板,设定模板编码
Template t = ve.getTemplate("无所谓", Constants.UTF8);
//设置初始化数据
VelocityContext context = new VelocityContext();
context.put("functionName", "系统管理");
context.put("parentMenuId", "0");
context.put("businessName", "system");
context.put("moduleName", "sysUser");
context.put("permissionPrefix", "system:sysUser");
//设置输出
StringWriter writer = new StringWriter();
//将环境数据转化输出
t.merge(context, writer);
// 简化操作
// ve.mergeTemplate("vm/sql/sql.vm", Constants.UTF8, context, writer);
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二种方式:
Velocity.evaluate
package com.redotsoft.gen.tmpl;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.StringWriter;
public class test2 {
private static String str = "-- 菜单 SQL\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 'admin', sysdate(), '', null, '${functionName}菜单');\n" +
"\n" +
"-- 按钮父菜单ID\n" +
"SELECT @parentId := LAST_INSERT_ID();\n" +
"\n" +
"-- 按钮 SQL\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}查询', @parentId, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}新增', @parentId, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}修改', @parentId, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}删除', @parentId, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 'admin', sysdate(), '', null, '');\n" +
"\n" +
"insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
"values('${functionName}导出', @parentId, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 'admin', sysdate(), '', null, '');";
/**
* 自定义VM资源加载器 测试
*/
public static void main(String[] args) {
// 创建引擎
Velocity v = new Velocity();
try {
//进行初始化操作
v.init();
//设置初始化数据
VelocityContext context = new VelocityContext();
context.put("functionName", "系统管理");
context.put("parentMenuId", "0");
context.put("businessName", "system");
context.put("moduleName", "sysUser");
context.put("permissionPrefix", "system:sysUser");
//设置输出
StringWriter writer = new StringWriter();
//将环境数据转化输出
v.evaluate(context, writer, "无所谓", str);
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}