To understand the development background of Spring Boot, you have to go back to the 1.0 release of Spring Framework in 2004, but everyone has been using the Spring Framework since they started learning Java, so we won’t expand too much.

As more and more enterprises and individuals use the Spring Framework for development, Spring has gradually changed from a simple and simple small Framework to a large and complete open source software. The boundaries of the Spring Framework have been constantly expanded to the point where Spring can do almost anything. Most of the open source components and middleware currently on the market are supported by Spring counterparts.

If you look at the current Spring website, you’ll find that its slogan is: Spring Makes Java Simple. It makes Java development much easier.

Although Spring’s component code is lightweight, its configuration is heavyweight. Every time Spring integrates open source software, it needs to add some basic configuration. Over time, as we develop larger projects, we often need to integrate many open source software. Therefore, the later development of large projects using Spirng requires the introduction of many configuration files, too many configurations are very difficult to understand, and prone to configuration errors, which brings a lot of burden to the developers.

Imagine a scenario where you need to develop a simple Hello World Web application using Spring. What should you do?

  • To create a project structure, you must include build files that depend on Maven or Gradle.

  • At a minimum, spring MVC and Servlet API dependencies need to be added

  • A web. XML that declares Spring’s DispatcherServlet

  • A Spring configuration with Spring MVC enabled

  • A controller class that responds “HelloWord” to an HTTP request

  • A Web application server for deploying applications, such as Tomcat

Throughout the process, we discovered that there was only one thing that was relevant to Hello Word functionality, and that was controllers. The rest were generic templates that Spring Web applications must use, and since all Spring Web applications use them, Then why are you providing all this stuff?

So it wasn’t until October 2012 that a guy named Mike Youngstrom created a feature request in Spring Jira to support containerless Web application architectures in the Spring Framework, He talks about configuring Web container services within the main container boot Spring container.

Jira. Spring. IO/browse/SPR -…

I think that Spring's web application architecture can be significantly simplified if it were to provided tools and a reference architecture that leveraged the Spring component and configuration model from top to bottom. Embedding and unifying the configuration of those common web container services within a Spring Container bootstrapped from a simple main() method. I think Spring's Web application architecture can be greatly simplified if you want to provide tools and reference architectures that leverage Spring components and configuration models from top to bottom. Embed and unify the configuration of those generic Web container services in the Spring container bootstrap with the simple main () method.Copy the code

The Spring development team was aware of these problems and needed a software solution to address them, while the concept of microservices was slowly gaining ground and developing small, stand-alone applications quickly became urgent.

Spring was at that intersection, so in early 2013, we started working on the Spring Boot project until The Release of Spring Boot1.0 in April 2014. Since then, Spring Boot has initiated a series of iterations and upgrades.

After seven years of development, the latest stable release of Spring Boot is version 2.6.0.

Development of Spring Boot

When Spring Boot was born, it attracted a lot of attention from the open source community, and individuals and enterprises began to try Spring Boot. It wasn’t until 2016 that Spring Boot was actually used in China. When I was making money, the company started using Spring Boot to build a Dubbo based microservices architecture in 2015. By now, Spring Boot is the first choice for almost every company.

Build Anything

Spring Boot is officially positioned as “BUILD ANYTHING,” as described in the official Spring Boot overview.

Spring Boot makes it easy to create stand-alone, Production-grade Spring based Applications that you can "just run". // Spring Boot allows you to easily create standalone, production-grade Spring based Applications. You just run it. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot Applications need minimal Spring configuration. // For the Spring platform and third-party libraries, we provide a solidify view that can save us a lot of trouble in building applications. Most Spring Boot applications require minimal Spring configuration.Copy the code

Spring Boot enables developers using the Spring Framework ecosystem to quickly and efficiently build applications based on Spring and the Spring ecosystem.

To help you understand this sentence, let’s do two small experiments. One is to build a project based on the traditional Spring MVC framework and the other is to use Spring Boot.

Spring MVC With Spring Boot

The differences and advantages of Spring Boot were compared through the construction process of Spring MVC project.

Spring MVC project construction process

  • Create a Maven-WebApp project

  • Add jar package dependencies

    Org.springframework spring-beans 5.2.5.RELEASE commons-logging commons-logging 1.2 spring-context spring-context-support spring-core spring-expression spring-web spring-webmvc

  • Modify the web. XML file

    contextConfigLocation classpath:applicationContext.xml

    org.springframework.web.context.ContextLoaderListener org.springframework.web.util.IntrospectorCleanupListener springmvc org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:dispatcher-servlet.xml springmvc /

  • Add the dispatcher-servlet.xml file to the Resources directory

    <context:component-scan base-package=”com.gupaoedu.controller” />

    mvc:annotation-driven/

  • Create a Controller

    @Controller public class HelloController { @RequestMapping(method = RequestMethod.GET,path = “/index”) public String index(Model model){ model.addAttribute(“key”,”Hello Gupao”); return “index”; }}

  • Modify the default index.jsp to set the parsing of el expressions

    <%@ page language=”java” contentType=”text/html; charset=utf-8″ pageEncoding=”utf-8″ isELIgnored=”false” %> ${key}

  • Run the project

Spring Boot setup process

You can build the scaffolding directly based on start.spring. IO.

Thinking and summarizing

Spring Boot allows developers using the Spring Framework ecosystem to quickly and efficiently build applications based on Spring and the Spring ecosystem.

Comparing the two build processes seems to make sense of what Spring Boot does. Of course, it does more than that, and will gradually reveal its true colors.

From the above example, we found that without Spring Boot, to build a Spring MVC Web application, there are a lot of things to do

  • The introduction of the jar package

  • Modify web.xml to add listening and intercepting

  • Create the Spring MVC core configuration file dispatcher-servlet.xml

  • Create a controller

  • Deployed to tomcat

This process may take 1-2 hours if you are not familiar with it, or longer if you are new to it. But Spring Boot, for beginners and veterans alike, can solve problems in minutes.

Understand convention over configuration

We know that Spring Boot is the product of convention by configuration, but what is convention by configuration?

Convention over configuration is a paradigm in software design designed to reduce the number of decisions software developers have to make and gain the benefits of simplicity without losing flexibility.

Simply put, the tool you use provides a convention by default. If the convention conforms to your expectations, you can omit the basic configuration. Otherwise, you need to configure it to get the way you want.

Convention is better than configuration in many ways. For example, traffic lights, stop on red and go on green, are traffic norms. You can stop at a red light because there is no obstacle in your way. But if everyone follows this agreement, both the smoothness and safety of the traffic will be better.

On a technical level, conventions can be expressed in many ways. For example, a company may have specific document formats, code submission specifications, interface naming conventions, database specifications, and so on. The point of these rules is to make the whole project more readable and maintainable.

Convention prevails over configuration in Spring Boot Web applications

So in the previous case, we can think about why Spring Boot can omit the original tedious and troublesome work? In fact, this work is not really omitted, but Spring Boot does it for us by default.

At this time, let’s think about the opposite. In the Spring Boot Web application, compared with the construction of Spring MVC framework, what aspects are its conventions reflected in the configuration?

  • By default, Spring Boot uses Maven’s directory structure. Src.main. Java stores the source code file src.main.resource Stores the resource file src.test. Java test code src.test.resource Tests the resource file target

  • Spring Boot supports four types of embedded Web containers, Tomcat Jetty Undertow Reactor (Tomcat Jetty Undertow Reactor), as described in Section 3.9 of the official Spring 2.2.6 documentation

  • Spring Boot provides two configuration files by default, application.properties and Application.yml. Spring Boot loads the parsed configuration from this configuration file by default.

  • Spring Boot uses the starter dependency to reduce third-party JAR dependencies.

These are the secrets of Spring Boot’s ability to build Web applications quickly and easily. Of course, convention over configuration in Spring Boot is not only reflected in these areas, but also in subsequent analysis.

Spring Boot integrates Mybatis

In fact, Spring Boot is essentially Spring, and if you had to draw some parallels from the evolution of technology, you could compare Jsp/ Servlets and Spring MVC, both of which can be used to develop Web projects, but in terms of usage, Spring MVC is much simpler to use.

Spring Boot and Spring are the equivalent of JSP/Servlet and Spring MVC. So it itself is not the so-called new technology, next, I take you to the Spring Boot integration Mybatis to achieve the basic operation of the data case, to continue to understand Spring Boot.

Create a Spring Boot application

Create a Web project

Introduce starter dependencies needed in the project

<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> < the groupId > org. Mybatis. Spring. The boot < / groupId > < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.2 < / version >  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>Copy the code

Create a database table

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `address` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Copy the code

Configuring database Connections

Spring: a datasource: url: JDBC: mysql: / / 192.168.13.106:3306 / test_springboot username: root password: root driver-class-name: com.mysql.cj.jdbc.DriverCopy the code

Develop the database access layer

Creating entity objects

public class User {
    private int id;
    private String name;
    private String address;
}
Copy the code

Create Mapper

@repository @mapper public interface UserMapper {User findById(int id); @repository @mapper public interface UserMapper {User findById(int id); @repository @mapper public interface UserMapper {User findById(int id);  List<User> list(); int insert(User user); int delete(int id); int update(User user); }Copy the code

Write a Mapper file

Create a usermapper. XML file in the resource file directory with the following contents

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD com. Example. Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.example.demo.mapper.UserMapper"> <resultMap id="resultMap" type="com.example.demo.entity.User"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="address" column="address"/> </resultMap> <select id="findById" resultMap="resultMap" parameterType="java.lang.Integer"> select * from t_user where id=#{id} </select> <select id="list" resultMap="resultMap"> select * from t_user </select> <insert id="insert" parameterType="com.example.demo.entity.User" keyProperty="id" useGeneratedKeys="true"> insert into t_user(name,address) values(#{name,jdbcType=VARCHAR},#{address,jdbcType=VARCHAR}) </insert> <delete id="delete" parameterType="java.lang.Integer"> delete from t_user where id=#{id} </delete> <update id="update" parameterType="com.example.demo.entity.User"> update t_user set name=#{name,jdbcType=VARCHAR},address=#{address,jdbcType=VARCHAR} where id=#{id,jdbcType=INTEGER} </update> </mapper>Copy the code

Define the service and its implementation

public interface IUserService {
​
    User findById(int id);
    List<User> list();
    int insert(User user);
    int delete(int id);
    int update(User user);
}
​
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
}
Copy the code

Create a Controller

@RestController public class Controller { @Autowired private IUserService userService; @GetMapping("/user/{id}") public User user(@PathVariable("id") int id){ return userService.findById(id); } @GetMapping("/users") public List<User> users(){ return userService.list(); } @PostMapping("/user") public String insertUser(User user){ int row=userService.insert(user); return row>0?" SUCCESS":"FAILED"; } @PutMapping("/user") public String updateUser(User user){ int row=userService.update(user); return row>0?" SUCCESS":"FAILED"; } @DeleteMapping("/user/{id}") public String deleteUser(@PathVariable("id") int id){ return userService.delete(id)>0?"SUCCESS":"FAILED"; }}Copy the code

Modify the configuration

  • Add the following annotation to Spring’s Main method to scan Mybatis Mapper file @mapperscan (“com.example.demo.mapper”)

  • Configure the address of the Mapper configuration file in application.yml

    mybatis: mapper-locations: classpath:*Mapper.xml id int, name varchar(20), address varchar(20))

Project package

  • mvn -Dmaven.test.skip -U clean install

  • java -jar xxx.jar

Simple summary

This code, I think, we should have written countless times, and in the case of integrating Mybatis based on Spring Boot, the core business logic is not reduced, it only reduces some cumbersome configuration, making us more focused on the business development level.

In simple terms, in Spring Boot-based projects, we only need to write Controlelr, Service, and Dao. Even in many cases we do not need to manage DAO, for example, the use of mybatis- Plus plug-in, can save a lot of fixed DAO layer logic.

So actually, there’s nothing new about Spring Boot, so if you look at most of the books on Spring Boot, and I’ve read almost all of them, they’re all about Spring Boot applications, and Spring Boot features. Because if you want to talk about Spring Boot, you have to come back to Spring. Spring Boot Programming Ideas, for example, is a book devoted to the Spring Framework. Because the kernel of Spring Boot is still the Spring Framework.

Spring Boot and microservices

Next, LET’s talk about Spring Boot and microservices.

What is Spring Cloud

First, let’s take a quick look at what microservices are. Microservices, as I understand them, are granular services that are further optimized for service-oriented architecture (SOA). If you are not very well understood, translated into the vernacular

A business system, originally in a separate WAR package. For better maintenance and performance, the WAR package is now broken down into separate business subsystems based on business latitude, each of which provides functionality related to the business domain and exposes API interfaces.

These services exchange data and communicate with each other to realize the functionality of the entire product.

These business subsystems actually represent a service, so the so-called microservice refers to the granularity of the service. As for the granularity of service what is micro, in fact, there is no fixed standard to measure. It is more about controlling the specific business granularity of each company.

Problems encountered in microservitization

After servitization, we will face many problems, such as service registration, service routing, load balancing, service monitoring and so on. These problems need to be solved by corresponding technologies, which is when Spring Cloud appears.

In short, Spring Cloud provides tools that allow developers to quickly build microservices applications, such as configuration management, service discovery, circuit breakers, smart routing, and so on, that work well in any distributed environment. Spring Cloud focuses on solving the following problems:

  • Distributed/versioned configuration.

  • Service registration and Discovery.

  • Routing indicates the service route.

  • Service-to-service calls indicates Service calls.

  • Load balancing.

  • Circuit Breakers d.

  • Global locks.

  • Leadership election and Cluster State, Leader election and cluster state

  • Distributed messaging.

It should be noted that Spring Cloud is not a new framework developed by the Spring team. It just integrates some excellent open source frameworks that solve common problems in microservices architecture based on Spring Cloud specifications. After encapsulation again through the Spring Boot framework, the complex configuration is shielded, providing developers with a good out-of-the-box microservice development experience. It is not hard to see that Spring Cloud is actually a set of specifications, and Spring Cloud Netflix, Spring Cloud Consul, and Spring CloudAlibaba are the implementations of Spring Cloud specifications.

Why is Spring Cloud based on Spring Boot

So why does Spring Cloud use Spring Boot as its infrastructure? The reason is simple

  1. Spring Cloud is a solution that focuses on the area of service governance, which is built on service architecture, so it still needs a hosting framework

  2. Spring Boot can simply be thought of as a scaffolding for quickly configuring Spring applications that can quickly develop individual microservices

In a microservice architecture, more and more microservice nodes need a mature and efficient scaffolding, and Spring Boot fits that need, as shown in the figure below.

The four core mechanics of Spring Boot

The four core mechanics of Spring Boot, if you must, They are @enableAutoConfiguration, Starter out of the box components, Actuator application monitoring, and Spring Boot CLI tools.

EnableAutoConfiguration

Starter

Tell Spring Boot what functionality it needs, and it can import the required libraries.

Actuator

Allows you to drill down into a running Spring Boot application

Spring Boot CLI

The Spring Boot CLI provides Spring Boot command line functionality for Spring Cloud. We can run Spring Cloud component applications by writing Groovy scripts. The steps are as follows.

  • Download the spring – the boot – cli spring boot cli: repo. Spring. IO/release/org…

  • Configuring environment Variables

  • Check the CLI version on the console spring — Version

  • Run applications on the CLI. We can compile and run Groovy source code using the run command. The Spring Boot CLI contains all the dependencies you need to run Groovy.

  • Groovy @restController Class HelloController {@getMapping (“/hello”) String hello(){return “hello World”; }}

  • Groovy executes Spring Run Hello. groovy on the console, and if you need to pass parameters, such as port, like the JVM parameters spring Run Hello. groovy — –server.port=9000

Four core features of Spring Boot

  • EnableAutoConfiguration

  • Starter

  • Actuator

  • Spring Boot CLI Spring Boot CLI provides Spring Boot command line functionality for Spring Cloud. We can run Spring Cloud component applications by writing Groovy scripts. The steps are as follows.

  • Download the spring – the boot – cli spring boot cli: repo. Spring. IO/release/org…

  • Configuring environment Variables

  • Check the CLI version on the console spring — Version

  • Run applications on the CLI. We can compile and run Groovy source code using the run command. The Spring Boot CLI contains all the dependencies you need to run Groovy.

  • Groovy @restController Class HelloController {@getMapping (“/hello”) String hello(){return “hello World”; }}

  • Groovy executes Spring Run Hello. groovy on the console, and if you need to pass parameters, such as port, like the JVM parameters spring Run Hello. groovy — –server.port=9000

Previous good articles:

How big is the gap between the programming level of ordinary companies and BAT factories?

I am proficient in all kinds of technical systems, but I have no interview opportunities….