Detailed explanation of the past and present life of Spring Boot and its relationship with Spring Cloud

To understand the development background of Spring Boot, you have to start from Spring Framework 1.0 in 2004 We started with the release of version 0, but we all used the Spring Framework from the beginning of learning Java, so we don't expand too much.

With more and more enterprises and individuals using the Spring Framework for development, Spring has slowly programmed a large and comprehensive open source software from a single and concise small framework. The boundary of the Spring Framework has been expanding. Now Spring can do almost anything. At present, most open source components and middleware on the market are supported by Spring corresponding components,

If you pay attention to the current official website of Spring, you will find that its slogan is: Spring makes Java Simple. It makes Java development easier.

Although Spring's component code is lightweight, its configuration is heavyweight. Every time Spring integrates an open source software, it needs to add some basic configuration. Slowly, as our development projects become larger and larger, we often need to integrate a lot of open source software. Therefore, many configuration files need to be introduced in the later development of large projects using Spirng, Too many configurations are very difficult to understand and prone to configuration errors, which brings a lot of burden to developers.

Imagine a scenario, that is, if you need to develop a simple Hello World Web application with spring, what actions should you do?

  • To create a project structure, you must include the build files that depend on Maven or Gradle.
  • At a minimum, you need to add spring mvc and servlet api dependencies
  • A web XML to declare the DispatcherServlet of spring
  • A spring configuration with Spring MVC enabled
  • A controller class, http request in response to HelloWord
  • A web application server for deploying applications, such as Tomcat

In the whole process, we found that only one thing is related to the function of Hello Word, that is, the controller. The rest are the general templates required by Spring Web applications. Since all Spring Web applications need them, why do you need to provide these things?

Therefore, until October 2012, Mike youngstrom created a function request in Spring Jira to support containerless Web application architecture in the Spring Framework. He talked about configuring Web container services in the spring container guided by the main container.

https://jira.spring.io/browse/SPR-9888

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 if we want to make full use of it from top to bottom Spring The tools and reference architecture of components and configuration models can be greatly simplified Spring of Web Application architecture. Through simple main()Method guided Spring Embed and unify those common in the container Web Configuration of the container service.

Moreover, the Spring development team is also aware of these problems and urgently needs a set of software to solve this problem. At this time, the concept of microservice is slowly rising, and the rapid development of small independent applications has become very urgent.

Spring happens to be at such an intersection, so it goes with the trend. In early 2013, it began to invest in the research and development of Spring Boot project until April 2014 Release 0. Since then, Spring Boot has started the process of iterating and upgrading some columns.

After seven years of development, so far, the latest stable version of Spring Boot is 2.6 Version 0.

Development of Spring Boot #

When Spring Boot was born, it attracted the attention of many open source communities, and some individuals and enterprises began to try to use Spring Boot. In fact, Spring Boot was not really used in China until 2016. When I was digging money before, in 2015, the company began to use Spring Boot to build a micro service architecture based on Dubbo. Up to now, Spring Boot is the first choice for almost all companies.

Build Anything#

Spring Boot is officially positioned as "build anying". The official overview of Spring Boot describes Spring Boot in this way.

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
// Through Spring Boot, you can easily create independent, production level applications based on Spring ecology. You just need to run them.
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 solidified view, which can reduce a lot of trouble in building applications. Most spring boot applications require only a minimal Spring configuration.

If you are not used to reading English documents, it may be complex to understand. In adult words, Spring Boot can help developers who use the Spring Framework ecosystem to quickly and efficiently build an application based on spring and spring ecosystem.

In order to make everyone understand this sentence more deeply, 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#

Compare the differences and advantages of Spring Boot through the construction process of Spring MVC project.

Spring MVC project construction process #

  • Create a maven webapp project

  • Add jar package dependency

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    
    spring-context
    spring-context-support
    spring-core
    spring-expression
    spring-web
    spring-webmvc
    
  • Modify web XML file

    <context-param><!--Configure context configuration path-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--Configure listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <!--to configure Spring MVC Request interception-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-patter>
    </servlet-mapping>
    
  • Add dispatcher servlet in the resources directory XML file

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <!-- scanning controller -->
    <context:component-scan base-package="com.gupaoedu.controller" />
    <!--Enable annotation driven-->
    <mvc:annotation-driven/>
    <!-- Define view parser -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
  • 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 project

Spring Boot setup process #

Directly based on start spring. IO this scaffold can be built.

Thinking and summarizing #

Let's go back to the definition of Spring Boot at the beginning. Spring Boot can help developers who use the Spring Framework ecosystem to quickly and efficiently build an application based on spring and spring ecosystem.

By comparing the two construction processes, it seems that you can understand the role of Spring Boot. Of course, its role is not only here, but will gradually uncover its true face in the future.

Through the above case, we find that without spring boot, we need to do a lot to build a Spring MVC web application

  • Import jar package
  • Modify web XML, add listening and interception
  • Create spring mvc core configuration file dispatcher servlet xml
  • Create controller
  • Deploy to tomcat

If you are not familiar with this process, it may take 1 ~ 2 hours. If you are a novice, it may take longer. However, spring boot, whether novice or veteran, can solve problems every minute.

Understanding conventions is better than configuration #

As we know, Spring Boot is the product of the concept of convention based configuration. So what is convention based configuration?

Convention over configuration is a paradigm of software design, which is mainly to reduce the number of decisions that software developers need to make and obtain simple benefits without failure.

In short, the tool you use will provide a convention by default. If the Convention is consistent with your expectations, you can omit those basic configurations. Otherwise, you need to achieve your expectations through relevant configurations.

There are many places where the agreement is better than the configuration. For example, traffic lights, stop at red lights and go at green lights are a traffic norm. You can stop at a red light because there is no obstacle to stop you. However, if everyone follows this agreement, both the smoothness and safety of the traffic will be better.

Compared with the technical level, the agreement is reflected in many places. For example, a company will have special document format, code submission specification, interface naming specification, database specification and so on. The meaning of these regulations is to make the whole project more readable and maintainable.

Embodiment of convention over configuration in Spring Boot Web application #

So in the previous case, we can think about why Spring Boot can omit the originally cumbersome and troublesome work? In fact, these tasks are not omitted in the real sense, but Spring Boot helps us implement them by default.

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

  • According to the project structure convention of Spring Boot, Spring Boot adopts Maven's directory structure by default, where

    src.main.java store source code files

    src.main.resource stores resource files

    src.test.java test code

    src.test.resource test resource file

    target compiled class files and jar files

  • Built in embedded Web container, in spring 2.2 Version 6 of the official document 3.9 In this chapter, it is explained that Spring Boot supports four embedded Web containers

    Tomcat

    Jetty

    Undertow

    Reactor

  • Spring Boot provides two configuration files by default, one is application The other is application yml. Spring Boot will parse the configuration from the configuration file by default and load it.

  • Spring Boot reduces the dependency of third-party jar s through starter dependency.

These are the secrets that Spring Boot can easily and quickly build a Web application. Of course, the superiority of Spring Boot convention over configuration is not only reflected in these places, but also reflected in the subsequent analysis.

Spring Boot integrates Mybatis #

In fact, the essence of Spring Boot is Spring. If you must find some similar comparisons in the process of technology development, you can compare Jsp/Servlet and Spring MVC. Both can be used to develop Web projects, but in use, the use of Spring MVC will be simpler.

Spring Boot and spring are equivalent to the relationship between JSP/Servlet and Spring MVC. Therefore, there is no so-called new technology in itself. Next, I will take you to the case of integrating Mybatis to realize the basic operation of data through Spring Boot to continue to understand Spring Boot.

Create Spring Boot application #

Create a Web project

Introduce the starter dependency required in the project #

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Create 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;

Configure database connection #

spring:
  datasource:
    url: jdbc:mysql://192.168.13.106:3306/test_springboot
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Develop database access layer #

Create a solid object #

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

Create Mapper #

//@Repository can be used as a tag in your persistence layer to automatically handle exceptions generated by database operations
@Repository
@Mapper
public interface UserMapper {

    User findById(int id);
    List<User> list();
    int insert(User user);
    int delete(int id);
    int update(User user);
}

Writing mapper files #

Create usermapper.com in the resource file directory XML file, as follows

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

Definition and implementation of service #

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;
}

Create 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";
    }

}

Modify configuration #

  • Add the following annotation on the Main method of Spring to scan the Mapper file of Mybatis

    @MapperScan("com.example.demo.mapper")
    
  • Configure the address of Mapper configuration file in application In YML

    mybatis:
      mapper-locations: classpath:*Mapper.xml
    

    id int,

    name varchar(20),

    address varchar(20)

)

Pack Project #

  • mvn -Dmaven.test.skip -U clean install
  • java -jar xxx.jar

Simple summary #

I think you have written this code countless times. In the case of integrating Mybatis based on Spring Boot, the core business logic is not reduced. It only reduces some cumbersome configurations, making us focus more on the business development level.

Simply put, in a Spring Boot based project, we only need to write Controlelr, Service and Dao. Even in many cases, we don't need to manage Dao. For example, using the mybatis plus plug-in can save a lot of fixed Dao layer logic.

In fact, there is nothing new about Spring boot. Therefore, you can see most of the books on Spring boot on the market. I have read almost all of these books, which basically explain the application of Spring boot and some feature analysis of Spring boot. Because once you want to talk about the principle of Spring boot, you will inevitably return to the content of Spring. For example, little brother Ma's Spring boot programming thought wrote a book, and a lot of it was about the Spring Framework. Because the Spring boot kernel is still the Spring Framework.

Spring Boot and microservices #

Next, let's talk about spring boot and microservices.

What is Spring Cloud #

First of all, let's briefly understand what microservices are. According to my understanding, microservices are granular services, which is a further optimization of service-oriented architecture (SOA). If you don't understand it well, translate it into vernacular

A business system is originally in a separate war package. Now, in order to better maintain and improve performance, the war package is divided into independent business subsystems according to the business dimension. Each subsystem provides the functions related to the business field and exposes the API interface.

These services exchange data and communicate with each other to realize the functions of the whole product.

These business subsystems actually represent a service. The so-called micro service refers to the granularity of the service. As for the granularity of services, there is no fixed measurement standard. It is more about the control of the specific business granularity of each company.

Problems encountered in microservicing #

After service, we will face many problems, such as service registration, service routing, load balancing, service monitoring and so on. These problems need corresponding technologies to solve. At this time, Spring Cloud appears.

In short, Spring Cloud provides some tools that allow developers to quickly build microservice applications, such as configuration management, service discovery, fusing, intelligent routing, etc. these services can work well in any distributed environment. Spring Cloud main
Committed to solving the following problems:

  • Distributed/versioned configuration.
  • Service registration and discovery.
  • Routing, service routing.
  • Service to service calls.
  • Load balancing.
  • Circuit Breakers.
  • Global locks.
  • Leader election and cluster state.
  • Distributed messaging, 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 to solve common problems in microservice architecture based on Spring Cloud specification through Spring Boot
After the framework is encapsulated again, it shields the complex configuration and provides developers with a good out of the box microservice development experience. It is not difficult to see that Spring Cloud is actually a set of specifications, and Spring Cloud Netflix, Spring Cloud consult and Spring CloudAlibaba are the implementation of Spring Cloud specifications.

Why is Spring Cloud based on Spring Boot #

Then why does Spring Cloud adopt Spring Boot as the basic framework? The reason is simple

  1. Spring Cloud is a solution focusing on the field of service governance, which relies on the service architecture, so it still needs a hosting framework
  2. Spring Boot can be simply regarded as a set of scaffolds for quickly configuring spring applications. It can quickly develop a single microservice

Under the microservice architecture, there are more and more microservice nodes, which need a set of mature and efficient scaffolds, and Spring Boot can just meet such needs, as shown in the figure below.

Four core mechanisms of Spring Boot #

If you must talk about it based on the characteristics of Spring Boot, you can only talk about the four core mechanisms of Spring Boot, namely @ EnableAutoConfiguration, Starter out of the box component, Actuator application monitoring, and Spring Boot CLI command line tool.

EnableAutoConfiguration#

Starter#

Tell Spring Boot what functions it needs, and it can introduce the required libraries.

Actuator#

Allows you to drill down into running Spring Boot applications

Spring Boot CLI#

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

  • Download spring boot cli

    Spring Boot CLI: JFrog

  • Configure environment variables

  • View the CLI version in the console spring --version

  • Run the application using the CLI. We can compile and run Groovy source code using the run command. Spring Boot CLI contains all the dependencies needed to run Groovy.

  • Create a hello Groovy files

    @RestController
    class HelloController {
    
    	@GetMapping("/hello")
    	String hello(){
    		return "Hello World";
    	}
    }
    
  • Execute spring run hello. On the console Groovy, if you need to pass parameters, such as port, is similar to 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 function for Spring Cloud. We can run Spring Cloud component applications by writing groovy scripts. The steps are as follows:

    • Download spring boot cli

      Spring Boot CLI: JFrog

    • Configure environment variables

    • View the CLI version in the console spring --version

    • Run the application using the CLI. We can compile and run Groovy source code using the run command. Spring Boot CLI contains all the dependencies needed to run Groovy.

    • Create a hello Groovy files

      @RestController
      class HelloController {
      
      	@GetMapping("/hello")
      	String hello(){
      		return "Hello World";
      	}
      }
      
    • Execute spring run hello. On the console Groovy, if you need to pass parameters, such as port, is similar to JVM parameters

      spring run hello.groovy -- --server.port=9000

Keywords: Spring Boot

Added by Phpdiot on Sun, 12 Dec 2021 09:50:12 +0200