Freemarker to generate Java code from a template

Source: Internet
Author: User
Tags generator

Freemarker based on the template generated Java code, this sentence, we must also know that its application, such as the popular dry principle, the principle of the meaning, can be briefly outlined as "Do not write duplicate code."

such as Java in the three-tier architecture, data access layer, business logic layer, the presentation layer, light three layers of the duplication of additions and deletions and related interface code.

How to do not write duplicate additions and deletions to the relevant code, you can refer to my MP Combat series and mybatis reverse engineering (for Java-related framework):

Maven project of MyBatis reverse engineering

MP Combat Series (vi) code generator explained

One of the MP Combat Series (vi) of the code generator is explained by the Volocity template engine. The principle is consistent with freemarker in nature, and you can understand that it is all based on existing templates for code generation.

The following is a brief example to explain:

First, import maven dependency

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>cn.test</groupId> <artifactid>freemarket </artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> < dependencies> <dependency> <groupId>org.freemarker</groupId> <ar            Tifactid>freemarker</artifactid> <version>2.3.23</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupi                D>org.apache.maven.plugins</groupid> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <conFiguration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!--<plugin> &LT;ARTIFAC Tid>maven-war-plugin</artifactid> <version>2.4</version> <configurat Ion> <warSourceDirectory>src/main/webapp</warSourceDirectory> </config uration> </plugin> </plugins> <finalname>${project.artifactid}</fi Nalname> </build></project>

Second, create a new com.freemarker.hello.templates package, and write the template file under the package TEST.FTL

 Package${classpath}; Public class${classname} {PrivateInteger ${id}; PrivateString ${username}; PrivateString ${password};  PublicInteger Get${id} () {return${id}; }         Public voidSet${id} (Integer ${id}) { This. ${id}=${id}; }         PublicString Get${username} () {return${username}; }     Public voidSet${username} (String ${username}) { This. ${username}=${username}; }         PublicString Get${password} () {return${password}; }         Public voidSet${password} (String ${password}) { This. ${password}=${password}; }}

Third, write run generate corresponding Java code class

 PackageCom.freemark.hello;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.OutputStreamWriter;ImportJava.io.Writer;ImportJava.util.HashMap;ImportJava.util.Map;Importfreemarker.template.Configuration;Importfreemarker.template.Template; Public classFreemarkerdemo {Private Static FinalString Template_path = "Src/main/java/com/freemark/hello/templates"; Private Static FinalString Class_path = "Src/main/java/com/freemark/hello";  Public Static voidMain (string[] args) {//Step1 Creating an Freemarker configuration instanceConfiguration Configuration =NewConfiguration (); Writer out=NULL; Try {            //Step2 getting the template pathConfiguration.setdirectoryfortemplateloading (NewFile (Template_path)); //Step3 Creating a data Modelmap<string, object> DataMap =NewHashmap<string, object>(); Datamap.put ("ClassPath", "Com.freemark.hello"); Datamap.put ("ClassName", "User"); Datamap.put ("id", "id"); Datamap.put ("UserName", "UserName"); Datamap.put ("Password", "password"); //step4 loading template filesTemplate template = Configuration.gettemplate ("TEST.FTL"); //STEP5 Generating DataFile docfile =NewFile (Class_path + "\" + "User.java"); out=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (docfile)); //step6 Output Filetemplate.process (DataMap, out); System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ The ^^ the User.java file was created successfully ^^!"); } Catch(Exception e) {e.printstacktrace (); } finally {            Try {                if(NULL!=Out )                {Out.flush (); }            } Catch(Exception E2) {e2.printstacktrace (); }        }    }}

Four, step three successful, refresh the project can, see Com.freemark.hello there is a user class

Summary: The example is very simple, and the freemarker is not strong enough to be seen here, but the example is instructive for beginners or developers who are ready to study freemarker.

For example: adherence to the "dry principle", for the improvement of development efficiency, helps very much.

Freemarker to generate Java code from a template

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.