Springboot combat 02 case-driven: How to analyze a Spring Web application?

In Lecture 01, we mentioned that the Spring family has many open source frameworks, and developers can implement various Spring applications based on these development frameworks. In Lecture 02, we do not intend to expand too much on the types and development methods of all these Spring applications, but mainly focus on developing services for Web scenarios based on Spring Boot, which is also the most common form of Internet applications. Before introducing the Spring Boot-based development model, let us briefly compare it with traditional Spring MVC.

Spring MVC VS Spring Boot

In a typical web application, the front-end and back-end usually use the HTTP protocol to complete the request and response. During the development process, it is necessary to complete URL address mapping, HTTP request construction, data serialization and deserialization, and the realization of each service’s own internal Business logic, as shown in the figure below:

Drawing 0.png

HTTP request response process

Let’s first look at the development steps required to complete the above development process based on Spring MVC, as shown in the following figure:

Drawing 1.png

Web application development process based on Spring MVC

The figure above includes the steps of using web.xml to define Spring’s DispatcherServlet, completing the configuration file to start Spring MVC, writing the Controller that responds to HTTP requests, and deploying the service to the Tomcat Web server. In fact, the development of Web applications based on the traditional Spring MVC framework has gradually exposed some problems. The typical ones are that the configuration work is too complicated and heavy, and the necessary application management and monitoring mechanisms are lacking.

If we want to optimize this set of development process, there are several points worth exploring, such as reducing unnecessary configuration work, enabling automatic management of dependencies, simplifying deployment and providing application monitoring, etc. And these optimization points happen to promote the birth of a new generation of development framework represented by Spring Boot. The development process based on Spring Boot is shown in the figure below:

Drawing 2.png

Web application development process based on Spring Boot

As can be seen from the above figure, it is significantly different from the Spring MVC-based development process in terms of configuration information management, service deployment and monitoring. As a new member of the Spring family, Spring Boot provides exciting features. The core value of these features is to ensure the simplicity of the development process, which is embodied in many aspects such as coding, configuration, deployment, and monitoring.

First, Spring Boot makes coding easier. We only need to add a dependency in Maven and implement a method to provide the RESTful style interface advocated in the microservice architecture.

Second, Spring Boot makes configuration easier. It converts the XML-based functional configuration method in Spring to Java Config, and provides a .yml file to optimize the original configuration scheme based on .properties and .xml files. The .yml file is more intuitive and convenient for the organization of configuration information. Also more powerful. At the same time, based on the automatic configuration feature of Spring Boot, default starter components are provided for various common tools and frameworks to simplify configuration.

Finally, in the deployment scheme, Spring Boot also created a new mode of one-click startup. The Spring Boot deployment package structure refers to the following figure:

Drawing 3.png

Spring Boot deployment package structure

From the figure, we can see that compared with the war package in the traditional mode, the Spring Boot deployment package not only contains business code and various third-party libraries, but also embeds the HTTP container. This package structure supports one-click startup of java –jar application.jar, without deploying an independent application server, and the entire application can be run by embedding Tomcat by default.

Finally, based on the newly provided Actuator component of Spring Boot, developers and operators can obtain the current runtime state of the application through the RESTful interface and monitor and alert the metrics behind these states. For example, you can get system environment variables through the “/env/{name}” endpoint, get all RESTful services through the “/mapping” endpoint, get thread working status through the “/dump” endpoint, and get through the “/metrics/{name}” endpoint JVM performance metrics, etc.

Dissecting a Spring Web Application

For a web application developed based on Spring Boot, its code organization needs to follow a certain project structure. In Lecture 02, unless otherwise specified, we will use Maven to manage structure and package dependencies in project engineering. The project structure of a typical web application is shown in the following figure:

Drawing 4.png

Spring Boot Web project structure diagram

In the picture above, there are a few places that need special attention. I have also marked them in the picture, which are package dependencies, startup classes, controller classes, and configuration. Let’s talk about this part and expand it separately.

Package dependencies

Spring Boot provides a series of starter projects to simplify the dependencies between various components. Taking the development of web services as an example, we need to introduce the spring-boot-starter-web project, and there is no specific code in this project, but some pom dependencies are included, as shown below:

  • org.springframework.boot:spring-boot-starter

  • org.springframework.boot:spring-boot-starter-tomcat

  • org.springframework.boot:spring-boot-starter-validation

  • com.fasterxml.jackson.core:jackson-databind

  • org.springframework:spring-web

  • org.springframework:spring-webmvc

It can be seen that this includes the spring-web and spring-webmvc components that will be used in traditional Spring MVC applications, so Spring Boot still completes the construction of the Web request response process based on these two components in the underlying implementation.

If we use Spring Boot 2.2.4, you will find that all the Spring components it depends on have been upgraded to version 5.X, as shown in the following figure:

Drawing 5.png

Schematic diagram of package dependencies for Spring Boot 2.2.4

Introducing the spring-boot-starter-web component in the application is just like introducing a normal Maven dependency, as shown below.

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Once the spring-boot-starter-web component is introduced, we can make full use of the automatic configuration mechanism provided by Spring Boot to develop web applications.

Start class

One of the most important steps in using Spring Boot is to create a Bootstrap starter class. The Bootstrap class structure is simple and solid, as shown below:

<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class HelloApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }
}
</code>

Obviously, a brand new annotation @SpringBootApplication is introduced here. In Spring Boot, the class with this annotation is the entry point of the entire application. On the one hand, it will start the entire Spring container, and on the other hand, it will automatically scan @Component, @Service, @Repository, @Controller, etc. under the code package structure Annotate and convert the classes corresponding to these annotations into Bean objects and load them into the Spring container.

Controller class

The Bootstrap class provides us with the entry of the Spring Boot application, which is equivalent to the basic skeleton of the application. Next, we can add the access entry of the HTTP request, which is a series of Controller classes in Spring Boot. The Controller here is conceptually consistent with the Controller in Spring MVC. A typical Controller class is as follows:

<code>@RestController
@RequestMapping(value = "accounts")
public class AccountController {
 
    @Autowired
    private AccountService accountService;
 
    @GetMapping(value = "/{accountId}")
    public Account getAccountById(@PathVariable("accountId") Long accountId) {
        Account account = accountService. getAccountById(accountId);
        return account;
    }
}
</code>

Please note that the above code contains three annotations @RestController, @RequestMapping and @GetMapping. Among them, @RequestMapping is used to specify the mapping relationship of the request address, the function of @GetMapping is equivalent to the @RequestMapping annotation specifying the GET request, and the @RestController annotation is an upgraded version of the @Controller annotation provided in traditional Spring MVC, which is equivalent to The combination of @Controller and @ResponseEntity annotations will automatically use JSON to implement serialization/deserialization operations.

Configuration file

We noticed that there is an application.yml file in the src/main/resources directory, which is the main configuration file in Spring Boot. For example, we can add configuration information such as ports, service names, and database access as shown below to this configuration file:

server:
  port: 8081
 
spring:
  application:
    name: orderservice
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/appointment
    username: root
    password: root

In fact, Spring Boot provides a powerful automatic configuration mechanism. If there are no special configuration requirements, developers can complete automatic integration of configuration information such as database access based on Spring Boot’s built-in configuration system.

Case Driven: SpringCSS

After introducing the basic process of creating a Web application based on Spring Boot, we will introduce the case system of this course, SpringCSS, where CSS is the abbreviation of Customer Service System. Customer service is a very common business scenario in e-commerce and health business scenarios. We will build a streamlined but complete system to demonstrate Spring Boot related design concepts and various technical components.

The business logic of customer service in real scenarios is generally very complex, and the purpose of the case system is to demonstrate the process of technology implementation, not to introduce specific business logic. Therefore, we have highly simplified the business process of the case, but all the technologies involved can be directly applied to the daily development process.

Overall architecture of SpringCSS

In SpringCSS, there is a customer-service, which is a Spring Boot application and the main service in the whole case system. In this service, we can adopt a classic layered architecture, which divides the service into Web layer, Service layer and Repository layer.

In the customer service system, we know that its core business is to generate customer work orders. For this reason, customer-service generally interacts with the user service account-service, but because the update of user account information is a low-frequency event, the implementation method we designed is that account-service actively updates the user account change information through message middleware. Push it to customer–service to complete the acquisition of user information. For order-service, its positioning is an order system, and customer-service also needs to query order information from this service. The entire system interaction process of SpringCSS is shown in the following figure:

Drawing 6.png

Overall Architecture Diagram of SpringCSS System

In the above figure, a number of technical components for building SpringCSS are introduced, and we will give a special introduction to these technical components in subsequent courses.

From case combat to principle analysis

Going one step further, building web applications based on the Spring Boot framework is a major goal of 02, but it is not the only goal. As an extension, we hope that through the study of excellent open source frameworks, we can master the operating mechanism behind each core component, and then have a deep understanding of the implementation principles of the architecture.

In this column, we will analyze the working principles of core components in Spring Boot by familiarizing ourselves with the source code. Typical scenarios include Spring Boot’s automatic configuration implementation principles, database access implementation principles, and HTTP remote call implementation principles.

When you learn the implementation principles of the above core components through in-depth analysis at the source code level, you can master the methods and skills in the system architecture design and implementation process, and guide the daily development work.

Summary and Preview

Case studies are the best way to grasp how a framework is applied. This course is a case-driven Spring Boot application development course. Today we mainly introduce the organizational structure and development methods of a typical Spring Boot web application in detail, and introduce the SpringCSS case system throughout the course system .

Here is a question for you to think about: When implementing a Spring Boot-based web application, what aspects are involved in the developer’s development work?

Starting from Lecture 03, we will analyze the Spring Boot framework based on the SpringCSS case, and the first thing to bear the brunt is its configuration system.

1.png

“Java Engineer High Salary Training Camp”

Practical training + interview simulation + referral from a big factory, if you want to improve your technical ability, enter a big factory to get a high salary, click the link to improve yourself!

Featured Comments

**wave:

What is the difference between application.yml and bootstrap.yml?

Instructor Response:

These two are configuration files, which are essentially the same. Bootstrap is loaded earlier than application. It can be understood that bootstrap is a system-level configuration file, and application is an application-level configuration file.

**wave:

Completion

Editor’s reply:

It’s great, the learning efficiency is so high, I give you a big praise~

**9137:

Are @ResponseEntity and @ResponseBody the same?

Instructor Response:

The @ResponseEntity annotation adds more content related to the http status code than the @ResponseBody annotation, which is equivalent to @ResponseStatus and @ResponseBody=
ResponseEntity

*Jay:

very down to earth

Editor’s reply:

Here are the refills for you, you must persist in finishing this down-to-earth course, come on~

*Yao:

that’s good

Editor’s reply:

Thank you cutie, I am very happy, please don’t stop!

**Forest:

SpringBoot is so popular that it must be mastered!

Editor’s reply:

come on~ you can do it

**Lu:

Domain object design and implementation, interface design and implementation (including business logic), database table structure, configuration files, that’s all that comes to mind

Instructor Response:

Yes.

**6781:

color

Editor’s reply:

Color color

* in:

I can’t add the lottery assistant, is it blocked?

Editor’s reply:

Please click this link http://to1.top/aqEvuqai to add a small assistant (it is recommended to open it with a mobile phone).