In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces you how to do SpringBoot scaffolding by hand! The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.
I. Preface
Why are we building wheels?
The core purpose of making wheels is to solve the condensing and reuse of common problems.
Although there are a large number of mature and stable wheels on the market to support system construction, that is, services, frames, components, tools, etc., for some larger companies, these wheels may not be able to support the service volume that the system needs to carry, so it is necessary to build some wheels.
Instead of repeating the wheel, the newly built wheel may not guarantee its stability. Generally used in the official website to launch the core wheel is suitable, such as SpringBoot, Netty, HBase and so on. But for some special scenarios, the solution tool components usually do not have fully matched wheels, such as SpringBoot scaffolding.
In fact, every larger company will have many components of similar technical services, such as RPC, database routing, registry, distributed tasks, MQ queue messages, and so on. At this time, the development of scaffolding needs to adapt these components to build a system architecture that meets the needs of their own company's technology stack. This is different from some smaller Internet companies, which can fully use the complete set of solutions provided by SpringBoot.
In addition, making wheels is not only the precipitation of personal technology, but also the accumulation of salary and treatment! Don't say you can't build a plane, it's just that you didn't provide a venue!
Is there any scene where wheels can be built?
All modules used under architecture infrastructure can become wheels. Usually, we are in these scenarios: load balancing, service gateways, service governance, framework languages, service components, data bearer, framework structure, deployment methods, tool plug-ins, and build the necessary wheels.
In fact, for a more mature Internet company, the wheels under most of the scenes have been basically completed. The rest are generally used to solve the general components of non-business logic in business scenarios, such as cache hot Key under high concurrency, Redis layer routing, non-unique short code generation of event invitations, and so on. However, the wheel construction of such scenarios is also very valuable, after stable use at the company level, it can also be extended to the market to obtain certain recognition, and better will be included in the Apache project.
What is scaffolding?
What is scaffolding? Is it a term for a particular platform?
Scaffolding is a meta-programming method of building database-backed software applications. It is a technique supported by some model-view-controller frameworks, in which the programmer may write a specification that describes how the application database may be used. The compiler uses this specification to generate code that the application can use to create, read, update and delete database entries, effectively treating the template as a "scaffold" on which to build a more powerful application.
Https://stackoverflow.com/questions/235018/what-is-scaffolding-is-it-a-term-for-a-particular-platform
Combined with the answers on stackoverflow, scaffolding is a metaprogramming method for building data-based applications. The programmer who created the system architecture wrote a specification describing how to use the database. The scaffolding can generate the corresponding frame code according to the rule specification. We use this model as scaffolding to build powerful applications more efficiently on scaffolding!
To put it bluntly, it is to simplify the simple work of common repetitive operations, eliminating the need for programmers to paste and copy little by little to clone an existing architecture. Just pass in the necessary parameters on the interface or public interface to create an application development framework.
Who provided the scaffolding?
1. Scaffolding on Spring official website
Recommended: ⭐⭐⭐⭐
Link: https://start.spring.io
Source code: https://github.com/spring-io/start.spring.io
Description: Spring Initializr is essentially a Web application, which can build a basic Spring Boot project structure through Web interface, Spring Tool Suite, IntelliJ IDEA and so on. At the same time, you can use its source code for local deployment
2. Ali Yun scaffolding
Recommended: ⭐⭐⭐⭐
Link: https://start.spring.io
Description: Aliyun Java Initializr and Spring Initializr are similar Web services, is the code framework generator, generate your code framework with one click, a complete tool chain, free IDEA plug-ins, easy to generate directly in IDE, perfect tool chain, free IDEA plug-ins, easy to generate directly in IDE, but also very suitable for domestic users' network environment.
In fact, these two scaffolding can well generate the project structure, so that programmers can quickly enter the development environment under a unified standard. Just rely on the support service of your choice and choose a different framework.
Fourth, hand-shake a scaffolding!
There is scaffolding, so why do you want to do it yourself?
The purpose of scaffolding is to quickly build the system framework under a unified standard, and introduce the configuration, components, services and testing needed in the system development process into the system development through configuration.
But sometimes the scaffolding commonly used in Internet companies is not suitable for use, because it does not introduce some self-developed components in the company, and it cannot be well integrated. If the scaffolding has been generated and requires developers to copy a large number of specific components, it destroys the ability of the scaffolding itself, but also destroys the norms and specifications.
Therefore, it is necessary to combine the development ability of scaffolding to package all kinds of specific components, services and configurations to achieve a unified scaffolding in line with the company's field.
So, this chapter takes you to look at a scaffolding, how to develop and implement. In fact, we are not too responsible, we can use the ability of freemarker to build a system framework.
1. Engineering framework
EasyRiggerInitializr └── src ├── main │ ├── java │ │ └── cn.bugstack.initializr.rigger │ │ ├── application │ └── IProjectGenerator.java │ │ ├── domain │ │ model ApplicationInfo. Java │ └── ProjectInfo.java │ └── service │ ├── module │ │ ├── impl │ ├── GenerationApplication.java │ │ │ ├── GenerationIgnore.java │ ├── GenerationPackageInfo.java │ ├── GenerationPom.java │ ├── GenerationTest.java │ └── GenerationYml.java │ │ └── BaseModule.java │ └── ProjectGeneratorImpl.java │ │ └── RiggerApplication.java │ └── resources │ ├── generator │ │ ├── application.ftl │ │ ignore.ftl │ ├── package-info.ftl │ │ ├── pom.ftl │ │ ├── test.ftl │ │ └── yml.ftl │ └── application.yml └── test └── java └── cn.bugstack.initializr.rigger.test └── ApiTest.java
The whole project used to create scaffolding is not complex, mainly through freemarker to all kinds of defined ftl template files to generate the corresponding system framework structure. It includes: project subject, framework structure, startup class, configuration file, test class and so on. We can also generate the corresponding ORM class and mapping relationship according to our own needs.
The whole project structure is partial to the DDD hierarchical structure, all the generation methods are built in the domain field, and the resources/generator definition generation template is not much different in other places.
Next, we briefly introduce the code of this project, so that we can understand how such a project is developed, and we can also continue to improve the structure we need through this project.
two。 Application layer definition generation class interface
Cn.bugstack.initializr.rigger.application.IProjectGenerator.java
Public interface IProjectGenerator {void generator (ProjectInfo projectInfo) throws Exception;}
The hierarchical structure of DDD usually defines the interface in the thin layer of application, and then the corresponding implementation is done in the domain layer of domain.
This interface is defined mainly to allow external callers to create an engineering framework through this interface.
3. FTL template definition
What is FreeMarker?
FreeMarker is a template engine: a general tool based on templates and data to be changed, and used to generate output text (HTML pages, e-mails, configuration files, source code, etc.). It is not for end users, but a Java class library, a component that programmers can embed in the products they develop.
The template is written as FreeMarker Template Language (FTL). It is a simple, proprietary language, not a mature programming language like PHP. That means preparing the data to be displayed in a real programming language, such as database queries and business operations, and then the template displays the prepared data. In the template, you can focus on how to present the data, while outside the template you can focus on what data to display.
FreeMarker online manual: http://freemarker.foofun.cn
3.1 application.ftl
Package ${packageName}; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @ SpringBootApplication public class ${className} {public static void main (String [] args) {SpringApplication.run (${className} .class, args);}}
3.2 pom.ftl
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE ${groupId} ${artifactId} ${version} ${name} ${description}
3.3 yml.ftl
Server: port: 8081
The above is just the basic ftl file used to generate the framework file. If you need some special judgment and logic, you can refer to the FreeMarker online manual and write the ftl file you need.
4. FTL generation file
Cn.bugstack.initializr.rigger.domain.service.module.impl.GenerationApplication.java
Service public class GenerationApplication extends BaseModule {private Logger logger = LoggerFactory.getLogger (GenerationApplication.class); public void doGeneration (ProjectInfo projectInfo, String projectsRoot, String lastPackageName, StringBuffer applicationJavaName) throws Exception {ApplicationInfo applicationInfo = new ApplicationInfo (projectInfo.getGroupId () + "." + lastPackageName, applicationJavaName.toString ()); String packagePath = applicationInfo.getPackageName (). Replace (".", "/") + "/" File file = new File (projectsRoot + projectInfo.getArtifactId () + "/ src/main/java/" + packagePath, applicationInfo.getClassName () + ".java"); / / write file super.writeFile (file, "application.ftl", applicationInfo); logger.info ("create main entry class Application.java {}", file.getPath ());}}
With regard to the use of ftl files, no matter which layer of files are used to generate them, they are basically common. This is only about the creation of Application.java.
It mainly includes three aspects: defining the input parameter ApplicationInfo, defining the file location / src/main/java/, and writing to the file super.writeFile.
5. Create a frame entry
Cn.bugstack.initializr.rigger.domain.service.ProjectGeneratorImpl.java
@ Service public class ProjectGeneratorImpl implements IProjectGenerator {private Logger logger = LoggerFactory.getLogger (ProjectGeneratorImpl.class); @ Resource private GenerationApplication generationApplication; @ Resource private GenerationYml generationYml; @ Resource private GenerationPom generationPom; @ Resource private GenerationTest generationTest; @ Resource private GenerationPackageInfo generationPackageInfo; @ Override public void generator (ProjectInfo projectInfo) throws Exception {URL resource = this.getClass () .getResource ("/") String projectsRoot = resource.getFile () + "/ projects/"; String lastPackageName = projectInfo.getArtifactId (). ReplaceAll ("-", ") .toLowerCase (); / / Startup class name String [] split = projectInfo.getArtifactId () .split ("-"); StringBuffer applicationJavaName = new StringBuffer () Arrays.asList (split) .forEach (s-> {applicationJavaName.append (s.substring (0,1). ToUpperCase () + s.substring (1)); applicationJavaName.append ("Application"); / / 1. Create Application.java generationApplication.doGeneration (projectInfo, projectsRoot, lastPackageName, applicationJavaName); / / 2. Generate application.yml generationYml.doGeneration (projectInfo, projectsRoot); / / 3. Generate pom.xml generationPom.doGeneration (projectInfo, projectsRoot); / / 4. Create a test class ApiTest.java generationTest.doGeneration (projectInfo, projectsRoot, lastPackageName, applicationJavaName); / / 5. Generate .gitignore generationIgnore.doGeneration (projectInfo, projectsRoot); / / 6. DDD four-layer description file generationPackageInfo.doGeneration (projectInfo, projectsRoot, lastPackageName, applicationJavaName);}}
The ProjectGeneratorImpl class is the concrete implementation of the application layer interface IProjectGenerator in the domain layer. The following are included here:
Create Application.java
Generate application.yml
Generate pom.xml
Create a test class ApiTest.java
Generate .gitignore
DDD four-layer description file
To sum up, is a brief introduction of the whole scaffolding generation, in fact, it is not much complex, mainly the definition and use of ftl files, this way to create scaffolding is still very convenient.
6. Test verification
Unit test @ Testpublic void test_IProjectGenerator () throws Exception {ProjectInfo projectInfo = new ProjectInfo ("cn.bugstack.demo", "web-test", "1.0.0-SNAPSHOT", "web-test", "Demo project for Spring Boot"); iProjectGenerator.generator (projectInfo);}
Test result
Scaffolding generates the created project under test-classes, and this path can also be configured to other paths.
With the newly generated project, you can open it through IDEA, just like the project we created manually.
5. Download the source code
Source code download: follow official account: bugstack wormhole stack, reply: scaffolding
Project description: SpringBoot scaffolding to simplify project construction. The current project project is still relatively simple, very suitable for newcomers to learn to use. In the future, we will gradually improve some functions on the basis of this version, integrating RPC, MQ, registry, gateway, and other components to facilitate selective construction and expansion.
VI. Summary
From the company's point of view, not repeating wheels is for the cost of the responsibilities and resources of various departments, but for individuals, we should not give up the opportunity to learn deeply about the knowledge stack just because we do not repeat the wheels.
Without these basic learning, we will not understand the transfer of technology, the extraction of services, or the refinement of components at all. Always do some API application shell over and over again, and there will be no growth in personal technology.
Finally, even if the company doesn't need you to build wheels, it doesn't matter, you can build them for yourself and share them with the Github community. On the one hand, it is their own learning summary, on the other hand, it is also the precipitation and contribution to the technology.
About how to do SpringBoot scaffolding by hand! So much for sharing here. I hope the above content can help you to some extent and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 237
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.