Java代码生成
因为使用spring boot开发项目的时候,需要经常创建新的service,entity,repository等代码,而且很多都是重复性的代码,也就是说可以进行模板化生成的代码。跟mybatis的代码生成不一样,我只需要生成一个新文件,然后有一些初始化的代码就行,因此实现起来也很简单
package com.iotxing.crm.util;
import java.io.File;
import java.io.FileWriter;
@SuppressWarnings("unchecked")
public class CodeGenerate {
/**
* @Author iotxing
* @Date 2019-06-06 14:52
*/
public static final String AUTHOR = "IOTXING";
//package title
public static final String ENTITYSRC = "com/iotxing/crm/model";
public static final String SERVICESRC = "com/iotxing/crm/service";
public static final String CONTROLLERSRC = "com/iotxing/crm/controller";
public static final String REPOSITORYSRC = "com/iotxing/crm/repository";
public static final String ENTITYPATH = "com.iotxing.crm.model";
public static final String SERVICEPATH = "com.iotxing.crm.service";
public static final String CONTROLLERPATH = "com.iotxing.crm.controller";
public static final String REPOSITORYPATH = "com.iotxing.crm.repository";
//创建实体类
public static void createEntity(String entityName) throws Exception {
String fileName = System.getProperty("user.dir") + "/src/main/java/" + ENTITYSRC + "/" + entityName + ".java";
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("package " + ENTITYPATH + ";\r\n\n\n");
fileWriter.write("public class " + entityName + " extends " + "BaseModel { \n\n");
fileWriter.write(" //code generate by iotxing \n\n");
fileWriter.write("\n\n\n");
fileWriter.write("}");
fileWriter.flush();
fileWriter.close();
}
public static void createService(String serviceName) throws Exception {
String fileName = System.getProperty("user.dir") + "/src/main/java/" + SERVICESRC + "/" + serviceName + ".java";
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("package " + SERVICEPATH + ";\r\n\n\n");
fileWriter.write("import org.springframework.stereotype.Service; \n\n\n");
fileWriter.write("@Service\n");
fileWriter.write("public class " + serviceName + " { \n\n");
fileWriter.write(" //code generate by iotxing \n\n");
fileWriter.write("\n\n\n");
fileWriter.write("}");
fileWriter.flush();
fileWriter.close();
}
public static void createRepository(String entityName) throws Exception {
String fileName = System.getProperty("user.dir") + "/src/main/java/" + REPOSITORYSRC + "/" + entityName + "Repository.java";
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("package " + REPOSITORYPATH + ";\r\n\n\n");
fileWriter.write("import " + ENTITYPATH +"."+entityName+ ";\r\n\n\n");
fileWriter.write("public interface " + entityName + "Repository extends BaseRepository<"+entityName+",Long> { \n\n");
fileWriter.write(" //code generate by iotxing \n\n");
fileWriter.write("\n\n\n");
fileWriter.write("}");
fileWriter.flush();
fileWriter.close();
}
}