Home > Java > javaTutorial > body text

How SpringBoot integrates freemarker to implement code generator

WBOY
Release: 2023-05-10 20:37:10
forward
1230 people have browsed it

    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.

    If a newly developed function requires adding 10 new tables, it will take at least 100 minutes based on this time. If you think about it carefully, you will actually find that most of the time is wasted on these simple and complicated functions. Gone into repetitive programming circles.

    Is there a way to standardize and publicize all these simple

    CURD codes? In this way, we can save a lot of time to invest in the development of business scenarios.

    The answer is yes, yes!

    I remember that the first thing I came into contact with in the early days was the

    MybatisGenertor toolkit. Through this toolkit, we can save most of the xml# in mybaits ##File curd writing work. There is also the familiar

    JPA

    , 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

    controller

    , service, entity , daoLayer, 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

    Mybatis-plus

    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

    crud

    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 engine

    freemarker 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>
    Copy after login

    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>
    }
    Copy after login
    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("文件创建成功");
    
        }
    }
    Copy after login
    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;
        }
    }
    Copy after login

    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 How SpringBoot integrates freemarker to implement code generatorfreemarker

    Go, it's very simple and fast to generate the code you want, and all the

    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

    framework. There is no

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template