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>
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; } }
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
