自动生成代码freemarker实现,教你java手写自动代码生成器,自动生成controller,service,mapper,等相关文件

自己闲着没事就是这些了些自动代码生成器,根据实体类,利用反射自动生成controller,service,mapper,等相关文件。下面是具体代码

如何使用可以参照我github上的项目,里面有具体的模板文件

https://github.com/kongGe55/mapper_test

这个项目结合了这个工具类的具体使用,大家可以根据自己的项目业务自由定制修改,甚至可以修改后生成后台html模板文件

package cn.haiwei.csovsserver;

import cn.haiwei.csovsserver.model.Role;
import cn.haiwei.csovsserver.model.ScheduledTasks;
import freemarker.template.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.util.*;

/**
 * ClassName: GeneratorCode
 * Description:
 * date: 2019/6/27 10:10
 *
 * @author JiLiugang
 * @version 1.0
 * @since JDK 1.8
 */
public class GeneratorCode {
    private final static String TEMPLATE_PATH = "src\\main\\java\\cn\\jiliugang\\package\\templates";
    private static Configuration configuration = null;
    private static List<Map<String,String>> fieldNameTypeMap = new ArrayList<>();
    private static Logger logger = LoggerFactory.getLogger(GeneratorCode.class);
    //项目主包名称
    private final static String packageName = "cn.jiliugang.package";
    public static void main(String[] args) {
        GeneratorCode.generatorCode(Role.class);
    }
    public static void generatorCode(Class entityClass) {
        //Configuration
        initConfiguration();
        //初始化查找实体类属性信息
        fieldNameTypeMap = getFieldInfo(entityClass);
        //得到对应渲染数据
        Map<String,Object> serviceClassInfo = getClassInfo(entityClass,"Service");
        Map<String,Object> implClassInfo = getClassInfo(entityClass,"ServiceImpl");
        Map<String,Object> mapperClassInfo = getClassInfo(entityClass,"Mapper");
        Map<String,Object> controllerClassInfo = getClassInfo(entityClass,"Controller");
        Map<String,Object> mapperXml = getClassInfo(entityClass,"MapperXml");
        generatorFile(mapperClassInfo);
        generatorFile(serviceClassInfo);
        generatorFile(implClassInfo);
        generatorFile(controllerClassInfo);
        generatorFile(mapperXml);
    }
    private static void initConfiguration() {
        configuration = new Configuration(Configuration.getVersion());
        try {
            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static List<Map<String, String>> getFieldInfo(Class entityClass) {
        //得到属性名
        Field[] declaredFields = entityClass.getDeclaredFields();
        List<Map<String, String>> fieldNameTypeMap = new ArrayList<>();
        for (Field field : declaredFields){
            Map<String, String> fieldMap = new HashMap<>();
            String type = field.getType().getSimpleName();
            String name = field.getName();
            //将属性名和对应类型放入map中
            fieldMap.put("name",name);
            fieldMap.put("type",type);
            fieldNameTypeMap.add(fieldMap);
        }
        return fieldNameTypeMap;
    }

    private static Map getClassInfo(Class entity,String typeName) {
        Map<String,Object> map = new HashMap<>();
        map.put("templateName",typeName+".ftl");
        map.put("packageName",packageName);
        //实体对象名称
        String className = entity.getSimpleName();
        map.put("className",className);
        map.put("classParamName",toLowerCaseFirstOne(className));
        map.put("EntityClassPath",entity.getName());
        //得到路径
        String realPath = null;
        String classPath = null;
        String classTypeName = null;
        Boolean isXml = false;
        if ("Service".equals(typeName)){
            realPath = "src.main.java."+packageName+".service";
            classPath = packageName+".service";
            classTypeName = className+"Service";
        }else if ("ServiceImpl".equals(typeName)){
            realPath = "src.main.java."+packageName+".service.impl";
            classPath = packageName+".service.impl";
            classTypeName = className+"ServiceImpl";
        }else if ("Mapper".equals(typeName)){
            realPath = "src.main.java."+packageName+".mapper";
            classPath = packageName+".mapper";
            classTypeName = className+"Mapper";
        }else if ("Controller".equals(typeName)){
            realPath = "src.main.java."+packageName+".controller";
            classPath = packageName+".controller";
            classTypeName = className+"Controller";
        }else if ("MapperXml".equals(typeName)){
            realPath = "src.main.resources.mapper";
            classTypeName = className+"Mapper";
            //应对嵌套渲染问题
            map.put("sqlPinJie","#{");
            isXml = true;
        }
        map.put("isXml",isXml);
        map.put("classTypeName",classTypeName);
        map.put("realPath",realPath);
        map.put("classPath",classPath);
        //日期
        map.put("date",new Date().toString());
        map.put("fields",fieldNameTypeMap);
        return map;
    }

    public static void generatorFile(Map<String,Object> classInfo){
        Writer out = null;
        // step4 加载模版文件
        Template template = null;
        try {
            template = configuration.getTemplate((String) classInfo.get("templateName"));
            // step5 生成数据
            String filePath = (String) classInfo.get("realPath");
            filePath = filePath.replaceAll("\\.","\\\\");
            File directory = new File(filePath);
            if (!directory.exists()){
                directory.mkdirs();
            }
            File docFile = null;
            if ((Boolean) classInfo.get("isXml")){
                docFile = new File(filePath + "\\" + classInfo.get("classTypeName")+".xml");
            }else {
                docFile = new File(filePath + "\\" + classInfo.get("classTypeName")+".java");
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // step6 输出文件
            template.process(classInfo, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        if ((Boolean) classInfo.get("isXml")){
            logger.info("----------------"+classInfo.get("classTypeName")+".xml 文件创建成功 !");
        }else {
            logger.info("----------------"+classInfo.get("classTypeName")+".java 文件创建成功 !");
        }
    }
    //首字母转小写
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值