4
头图

To understand the development background of Spring Boot, you have to start with the release of Spring Framework 1.0 in 2004, but everyone has used Spring Framework since they started learning Java, so I won't do too much.

As more and more companies and individuals use the Spring Framework for development, Spring is slowly programming a large and complete open source software from a single and concise small framework. The boundaries of the Spring Framework continue to expand, and now Spring can almost do anything. Currently, most of the open source components and middleware on the market are supported by Spring's corresponding components.

If you pay attention to Spring's current official website, you will find that his 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, some basic configuration needs to be added. Slowly, as the projects we develop become larger and larger, often A lot of open source software needs to be integrated, so the later use of Spirng to develop large-scale projects requires the introduction of many configuration files. Too many configurations are very difficult to understand and easy to configure errors. This brings a lot of burden to developers.

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

  • Creating a project structure must include build files that rely on Maven or Gradle.
  • At least need to add spring mvc and servlet api dependency
  • A web.xml that declares spring's DispatcherServlet
  • A spring configuration with Spring MVC enabled
  • A controller class that responds to http requests with "HelloWord"
  • A web application server for deploying applications, such as Tomcat

Throughout the process, we found that there is only one thing related to the Hello Word function, that is the controller, and the rest are the common templates that Spring developed web applications must use, since all Spring web applications must use To them, why do you want to provide these things?

So, until October 2012, a person named Mike Youngstrom (Youngstrom) created a feature request in Spring Jira, requiring support for containerless web application architecture in the Spring Framework. He talked about booting in the main container Configure the Web container service in the spring 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.
我认为,如果要提供从上到下充分利用Spring组件和配置模型的工具和参考体系结构,则可以大大简化Spring的Web应用程序体系结构。在通过简单main()方法引导的Spring容器中嵌入和统一那些通用Web容器服务的配置。

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 microservices is slowly rising, and the rapid development of tiny independent applications has become urgent.

And Spring happened to be at such an intersection, so in early 2013, it started to invest in the research and development of the Spring Boot project until April 2014, when the Spring Boot 1.0 version was released. Since then, Spring Boot has started a series of iterations and upgrades.

After 7 years of development, so far, the latest stable version of Spring Boot is version 2.6.0.

The development of Spring Boot

When Spring Boot was first born, it attracted a lot of attention from the open source community, and some individuals and companies began to try to use Spring Boot. In fact, it wasn't until 2016 that Spring Boot was really used in China. When I was digging for money, the company began to use Spring Boot in 2015 to build a Dubbo-based microservice architecture. Up to now, Spring Boot is almost the first choice of all companies.

Build Anything

Spring Boot is officially positioned as "BUILD ANYTHING", the official Spring Boot overview describes Spring Boot this way.

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
// 通过Spring Boot可以轻松的创建独立的、生产级别的基于Spring 生态下的应用,你只需要运行即可。
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.
//对于Spring平台和第三方库,我们提供了一个固化的视图,这个视图可以让我们在构建应用是减少很多麻烦。大部分spring boot应用只需要最小的Spring 配置即可。

If you are not accustomed to reading English documents, it may be more complicated to understand. The translation is: Spring Boot can help developers who use the Spring Framework ecosystem to quickly and efficiently build an application based on Spring and the spring ecosystem.

In order to give everyone a deeper understanding of 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

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

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 the web.xml file

    <context-param><!--配置上下文配置路径-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--配置监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <!--配置Spring MVC的请求拦截-->
    <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 the dispatcher-servlet.xml file in the resources directory

    <?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">
    
    <!-- 扫描 controller -->
    <context:component-scan base-package="com.gupaoedu.controller" />
    <!--开启注解驱动-->
    <mvc:annotation-driven/>
    <!-- 定义视图解析器 -->
    <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 and 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 build process

Just build it directly based on the scaffolding of start.spring.io.

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 the spring ecosystem.

Comparing the two construction processes, it seems that you can understand the role of Spring Boot. Of course, its role is not only that, the follow-up will gradually reveal its true face.

Through the above case, we found that if there is no spring boot, there are many things that need to be done to build a Spring MVC web application.

  • Introduce the jar package
  • Modify web.xml, add monitoring and interception
  • Create the 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 to 2 hours. If you are a novice, it may take longer. But spring boot, whether you are a novice or a veteran, can solve the problem in minutes.

Understanding conventions is better than configuration

We know that Spring Boot is the product of the contract due to the configuration concept, so what is the contract due to the configuration?

Agreement over configuration is a paradigm of software design, mainly to reduce the number of decisions software developers need to make, and to obtain simple benefits without losing flexibility.

To put it simply, the tool you use will provide a convention by default. If this convention is in line with your expectations, you can omit those basic configurations. Otherwise, you need to use related configurations to achieve the way you expect. .

Conventions are better than configuration in many places. For example, such as traffic lights, stop at red light, and go at green light, this is a traffic regulation. You can stop at the red light, because there is no obstacle blocking you at this time. But if everyone follows this agreement to implement, then both the smoothness of the traffic and the safety are better.

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

The 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 original tedious and troublesome work? In fact, these tasks are not omitted in the true sense, but Spring Boot helps us implement it by default.

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

  • The project structure convention of Spring Boot, Spring Boot adopts Maven's directory structure by default, among which

    src.main.java stores 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 the official document of Spring 2.2.6 version 3.9 chapter, it is stated that Spring Boot supports four embedded web containers

    Tomcat

    Jetty

    Undertow

    Reactor

  • Spring Boot provides two configuration files by default, one is application.properties and the other is application.yml. By default, Spring Boot will parse the configuration from the configuration file for loading.
  • Spring Boot uses starter dependency to reduce the dependency of third-party jars.

These are the secrets of how Spring Boot can build a web application quickly and easily. Of course, Spring Boot's contract is better than configuration not only in these places, but also in the follow-up analysis, we will see the embodiment of Spring Boot's contract better than configuration.

Spring Boot integrates Mybatis

In fact, the essence of Spring Boot is Spring. If you must find some similar comparisons in the process of technological 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.

And Spring Boot and Spring are equivalent to the relationship between JSP/Servlet and Spring MVC back then. So there is no so-called new technology in itself. Next, I will take you to use Spring Boot to integrate Mybatis to realize the basic operation of data to continue to get to know Spring Boot.

Create Spring Boot application

Create a web project

Introduce the starter dependencies needed 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

1587536145803

Create entity objects

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

Create Mapper

//@Repository可以支持在你的持久层作为一个标记,可以去自动处理数据库操作产生的异常
@Repository
@Mapper
public interface UserMapper {

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

Write the mapper file

Create a UserMapper.xml file in the resource file directory, the content is 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>

Define service and implement

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

}

Change setting

  • Add the following annotations to Spring's Main method to scan Mybatis Mapper files

    @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 packaging

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

Brief summary

This code, I think, everyone should have written it countless times, and in the case of integrating Mybatis based on Spring Boot, the core business logic has not been reduced, it only reduced some cumbersome configurations, making us more focused 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.

So in fact, Spring Boot has nothing new, so you see most of the books on the market that talk about spring boot. I have read almost all of these books. They basically explain the application of Spring Boot and some features of Spring Boot. analyze. Because once you want to talk about the principles of Spring Boot, you will inevitably return to the content of Spring. For example, Xiao Ma's Spring Boot programming thought book, and most of it is about Spring Framework. Because the core of Spring Boot is Spring Framework.

Spring Boot and microservices

Next, I will tell you about spring boot and microservices.

What is Spring Cloud

First of all, we have to briefly understand what a microservice is. According to my understanding, a microservice is a fine-grained service, which is a further optimization of a service-oriented architecture (SOA). If you don’t understand well, translate it into vernacular

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

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

And these business subsystems actually represent a service, so the so-called microservices refer to the granularity of this service. As for the granularity of a service, there is actually no fixed measurement standard. More is to control the specific business granularity of each company.

Problems encountered in microservices

After becoming a service, it will face many problems, such as service registration, service routing, load balancing, service monitoring and so on. These problems all need corresponding technology to solve, this time, Spring Cloud appeared.

To put it simply, Spring Cloud provides some tools that allow developers to quickly build microservice applications, such as configuration management, service discovery, circuit breakers, intelligent routing, etc. These services can work well in any distributed environment. Spring Cloud main
Committed to solving the following problems:

  • Distributed/versioned configuration, distributed and versioned configuration.
  • Service registration and discovery, service registration and discovery.
  • Routing, service routing.
  • Service-to-service calls, service calls.
  • Load balancing, load balancing.
  • Circuit Breakers, circuit breakers.
  • Global locks, global locks.
  • Leadership election and cluster state, 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 only integrates some of the more excellent open source frameworks that solve common problems in the microservice architecture based on the Spring Cloud specification.
After the framework is packaged again, the complex configuration is shielded, providing 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 Consul, and Spring Cloud Alibaba are the implementations of Spring Cloud specifications.

Why Spring Cloud is based on Spring Boot

So why does Spring Cloud use Spring Boot as the basic framework? the reason is simple

  1. Spring Cloud is a solution that focuses on the field of service governance, and service governance relies on the service architecture, so it still needs a hosting framework
  2. Spring Boot can be simply thought of as a set of scaffolding for rapid configuration of Spring applications, which can quickly develop a single microservice

Under the microservice architecture, there are more and more microservice nodes, and a set of mature and efficient scaffolding is required. Spring Boot can just meet this demand, as shown in the following figure.

image-20211124135348046

Four core mechanisms of Spring Boot

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

EnableAutoConfiguration

Starter

Tell Spring Boot what features are needed, and it can introduce the needed libraries.

Actuator

Allows you to dive into running Spring Boot applications

Spring Boot CLI

Spring Boot CLI provides Spring Boot command line functions for Spring Cloud. We can run Spring Cloud component applications by writing groovy scripts. Proceed as follows,

  • Download spring-boot-cli

    Spring Boot CLI:https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.2.6.RELEASE/spring-boot-cli-2.2.6.RELEASE-bin.zip

  • Configure environment variables
  • Check the CLI version on the console spring --version
  • Use CLI to run the application. We can use the run command to compile and run Groovy source code. Spring Boot CLI contains all the dependencies needed to run Groovy.
  • Create a hello.groovy file

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

  • spring run hello.groovy in the console, if you need to pass parameters, such as port, similar to JVM parameters

    spring run hello.groovy -- --server.port=9000
Copyright statement: All articles in this blog, except for special statements, adopt the CC BY-NC-SA 4.0 license agreement. Please indicate the reprint from Mic takes you to learn architecture!
If this article is helpful to you, please help me to follow and like. Your persistence is the motivation for my continuous creation. Welcome to follow the WeChat public account of the same name for more technical dry goods!

跟着Mic学架构
810 声望1.1k 粉丝

《Spring Cloud Alibaba 微服务原理与实战》、《Java并发编程深度理解及实战》作者。 咕泡教育联合创始人,12年开发架构经验,对分布式微服务、高并发领域有非常丰富的实战经验。