search
HomeJavajavaTutorialHow 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.

    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>

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

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

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

    Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

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

    JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

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

    JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

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

    Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

    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.

    Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

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

    What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

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

    Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

    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.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Article

    Hot Tools

    MantisBT

    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

    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

    SublimeText3 Chinese version

    Chinese version, very easy to use

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor