How SpringBoot integrates freemarker to implement code generator
1. Introduction
In the actual software project development process, I can tell you responsibly that if you actually write code For more than 5 years, you can say that you have completely exhausted the development of simple functional requirements such as additions, deletions, modifications and searches, at least I am this type.
However, it is undeniable that the vast majority of software functions, down to the most basic unit, are basically the addition, deletion, modification, and query of a single table!
It’s just that as user needs continue to increase, things that might have been done with a single table in the past may now require multiple tables or multiple libraries. The code layer is like stacking blocks, and the more they are stacked, the more complex they become. .
I remember when I was working on a project in the early days, every time I added a single table to the project, I needed to rewrite a set of CURD## at the code level in accordance with the idea of the
MVC framework. # code, it will take at least 20 minutes to write all the basic additions, deletions, modifications and checks. If you are fast, it will take 10 minutes at the fastest.
CURD codes? In this way, we can save a lot of time to invest in the development of business scenarios.
MybatisGenertor toolkit. Through this toolkit, we can save most of the
xml# in mybaits
##File curd
writing work. There is also the familiar
, which has a set of public persistence layer dynamic proxy classes, which can automatically generate SQL
statements based on the name, which can save development time. A lot of things happen. But I am a lazy person. I want to build a tool from
, service
, entity
, dao
Layer, all crud
codes, including unit test classes, are automatically generated by tools. There are many tools like this on the Internet now, such as the
plug-in that we are familiar with, which can do this and is also very easy to use. But some companies don’t like it, and the reason is very simple. Many public methods in it are encapsulated too deeply, and many
sql
are all Dynamically generated, you can't see it at all. In short, it’s not within their control. Many programmers always have various doubts~~
Of course, there is also an obvious doubt about microservices. Development cannot be fully supported. For example, if your project is developed using the
SpringBoot Dubbo combination, the controller
generated at this time is completely useless and tasteless. So in this case, you have to develop your own code generator based on the current project software development rules to meet the needs of rapid development.
Now I will briefly introduce how to develop a code generator by yourself. The process is as follows!
2. Code Practice
In fact, developing a code generator is not as complicated as everyone thinks. The most important technology used among them is to use templates to generate Code
, such as the template enginefreemarker we often use, can help us achieve this. 2.1. First, we add the freemarker dependency package
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>2.2, and then create a code template Let’s take dynamically creating an entity class as an example and write a template for the entity class.
entity.java.ftl
, where${} defines dynamic variables.
package ${package}; import java.io.Serializable; /** * <p> * ${tableComment} * </p> * * @author ${author} * @since ${date} */ public class ${entityClass} implements Serializable { private static final long serialVersionUID = 1L; <#--属性遍历--> <#list columns as pro> /** * ${pro.comment} */ private ${pro.propertyType} ${pro.propertyName}; </#list> <#--属性get||set方法--> <#list columns as pro> public ${pro.propertyType} get${pro.propertyName?cap_first}() { return this.${pro.propertyName}; } public ${entityClass} set${pro.propertyName?cap_first}(${pro.propertyType} ${pro.propertyName}) { this.${pro.propertyName} = ${pro.propertyName}; return this; } </#list> }
2.3. Finally generate the target code
Finally we write a test class based on freemarker
!public class CodeGeneratorDemo { public static void main(String[] args) throws IOException, TemplateException { Map<String, Object> objectMap = new HashMap<>(); //定义包路径 objectMap.put("package", "com.example.test"); //定义实体类 objectMap.put("entityClass", "Student"); //定义实体类属性 List<Map<String, Object>> columns = new ArrayList<>(); //姓名字段 Map<String, Object> column1 = new HashMap<>(); column1.put("propertyType", "String"); column1.put("propertyName", "name"); column1.put("comment", "姓名"); columns.add(column1); //年龄字段 Map<String, Object> column2 = new HashMap<>(); column2.put("propertyType", "Integer"); column2.put("propertyName", "age"); column2.put("comment", "年龄"); columns.add(column2); //定义类的属性 objectMap.put("columns", columns); //定义作者 objectMap.put("author", "张三"); //定义创建时间 objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date())); //定义类描述 objectMap.put("tableComment", "学生信息"); //生产目标代码 Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); configuration.setDefaultEncoding(Charset.forName("UTF-8").name()); configuration.setClassForTemplateLoading(CodeGeneratorDemo.class, "/"); Template template = configuration.getTemplate("/templates/entity.java.ftl"); FileOutputStream fileOutputStream = new FileOutputStream(new File("../src/main/java/com/example/generator/Student.java")); template.process(objectMap, new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8").name())); fileOutputStream.close(); System.out.println("文件创建成功"); } }
Run the program and the output file results are as follows!
package com.example.test; import java.io.Serializable; /** * <p> * 学生信息 * </p> * * @author 张三 * @since 2021-08-22 */ public class Student implements Serializable { private static final long serialVersionUID = 1L; /** * 姓名 */ private String name; /** * 年龄 */ private Integer age; public String getName() { return this.name; } public Student setName(String name) { this.name = name; return this; } public Integer getAge() { return this.age; } public Student setAge(Integer age) { this.age = age; return this; } }Consistent with the expected effect, successfully generated! For example, I use this method. First, all the codes to be generated by the tool are defined through templates.
Then by connecting to the database, query the table structure that needs to be automatically generated, encapsulate it into data rendering parameters, and finally pass it into freemarker
crud of a single table is done in one step!
The following is a code generator customized and developed by the editor based on the current project. The project is developed using the
SpringBoot Dubbo
Controller layer. Everything in the screenshot All codes are generated using a code generator and can be run directly through unit tests. Development is very fast!
The above is the detailed content of How SpringBoot integrates freemarker to implement code generator. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor
