JAVA-8-[SpringBoot] entry program case and principle analysis

Spring Boot Framework Getting Started Tutorial (Quick Learning Edition)
Spring Boot Tutorial BooTWiki.COM

1 Spring Boot

Spring Boot is a new set of open source framework provided by the Pivotal (critical) team based on Spring. Its purpose is to simplify the construction and development process of Spring applications. Spring Boot removes a large number of XML configuration files and simplifies complex dependency management.

Spring Boot has all the excellent features of Spring. What Spring can do, Spring Boot can do, and it is easier to use, more functional, and more stable and robust. With the popularity of microservice technology in recent years, Spring Boot has become a hot technology nowadays.

Spring Boot integrates a large number of commonly used third-party library configurations. These third-party libraries in Spring Boot applications can be almost out-of-the-box with zero configuration. Most Spring Boot applications only need very With a small amount of configuration code (Java-based configuration), developers can focus more on business logic.

1.1 What is Spring Boot

简化Spring应用开发的一个框架;
整个Spring技术栈的一个大整合;
J2EE开发的一站式解决方案;

We all know that Spring applications require a lot of configuration, and various XML configurations and annotation configurations are dazzling and extremely error-prone, so Spring was once called "configuration hell".

In order to simplify the construction and development process of Spring applications, the Pivotal team provides a new open source framework based on Spring, which is Spring Boot.

Spring Boot has all the excellent features of Spring. What Spring can do, Spring Boot can do, and it is easier to use, more functional, and more stable and robust. With the popularity of microservice technology in recent years, Spring Boot has also become a hot technology nowadays.

Spring Boot provides a large number of out-of-the-box dependent modules, such as spring-boot-starter-redis, spring-boot-starter-data-mongodb and spring-boot-starter-data-elasticsearch wait. These dependent modules provide a large amount of automatic configuration for Spring Boot applications, so that Spring Boot applications can run with only a small amount of configuration or even zero configuration, freeing developers from Spring's "configuration hell", and more Focus on the development of business logic.
Spring Boot has the following characteristics:
(1) Independently running Spring project
Spring Boot can run independently in the form of a jar package, and the Spring Boot project can run only through the command "java–jar xx.jar".
(2) Embedded Servlet container
Spring Boot uses an embedded Servlet container (such as Tomcat, Jetty or Undertow, etc.), and the application does not need to be packaged as a WAR package.
(3) Provide starter to simplify Maven configuration
Spring Boot provides a series of "starter" project object models (POMS) to simplify Maven configuration.
(4) Provides a large number of automatic configurations.
Spring Boot provides a large number of default automatic configurations to simplify project development. Developers also modify the default configurations through configuration files.
(5) Self-contained application monitoring
Spring Boot can provide monitoring for running projects.
(6) No code generation and xml configuration
Spring Boot does not require any xml configuration to implement all Spring configurations.

1.2 Introduction to Microservices

1. Monolithic application

一个单体应用程序把它所有的功能放在一个单一进程中。

2. Microservices

2014年,Martin Fowler
微服务:架构风格
一个应用应该是一组小型服务;可以通过HTTP的方式进行互通。

每一个功能元素最终都是一个可独立替换和独立升级的软件单元。

1.3 Configure the development environment

Create a Spring Boot project with IDEA.

Spring Boot	2.x
JDK	8.0 及以上版本
Maven 	3.x
IntelliJ IDEA	14.0 以上

1.4 Create a Spring Boot project

Intellij IDEA can generally create Spring Boot projects in two ways:
Method 1: Create with Maven.
Method 2: Use Spring Initializr to create.

This is created using Maven.
1. Use IntelliJ IDEA to create a Maven project named helloworld.
D:\CODEjava\helloworld
2. Add the following configuration to the pom.xml of the Maven project to import Spring Boot-related dependencies.
3. Under the net.biancheng.www package, create a main program named helloWorldApplication to start the Spring Boot application. The code is as follows.
4. In order to see the effect more clearly, we create a controller package under the net.biancheng.www package, and create a Controller named HelloController in this package, the code is as follows.

1.4.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

</project>

1.4.2 helloWorldApplication.java

package net.biancheng.www;

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

The entry point of a Spring Boot Application is the class annotated with @SpringBootApplication. This class should have the main method to run the Spring Boot application. The @SpringBootApplication annotation includes auto-configuration, component scanning, and Spring Boot configuration.
If you add @SpringBootApplication annotation to your class, you don't need to add @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotations. The @SpringBootApplication annotation includes all other annotations.

1.4.3 HelloController.java

package net.biancheng.www.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    
    
    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
    
    
        return "Hello World!";
    }
}

1.4.4 Start the project

By default, the Spring Boot project will create a main program startup class named ***Application, which uses a combined annotation @SpringBootApplication to enable the automatic configuration of Spring Boot. In addition, the startup class contains a main () method to start the project.

Run the main() method in the startup class HelloworldApplication directly to start the project, and the result is as shown in the figure below.
insert image description here
Note: Spring Boot integrates Tomcat internally, and there is no need to manually configure Tomcat. Developers only need to pay attention to specific business logic.
Restart the Spring Boot project, and then visit "http://localhost:8080/hello" in the address bar.
insert image description here

2 Spring Boot starter

If a traditional Spring project wants to run, it not only needs to import various dependencies, but also configure various XML configuration files, which is very cumbersome, but after the Spring Boot project is created, it can be done without writing any code or performing any configuration. Run directly, thanks to Spring Boot's starter mechanism.

所有Spring Boot启动程序都遵循相同的命名模式
spring-boot-starter-*,其中*表示它是应用程序的一种类型。

(1) The spring-boot-starter-actuator dependency is used to monitor and manage the application.
(2) The spring-boot-starter-security dependency is used for Spring Security.
(3) The spring-boot-starter-web dependency is used to write the Rest endpoint.
(4) The spring-boot-starter-thymeleaf dependency is used to create the web application.
(5) The spring-boot-starter-test dependency is used to write test cases.

2.1 starter

Spring Boot extracts all kinds of scenarios in the daily enterprise application development and makes starters one by one. The starter integrates various dependencies that may be used in this scenario. Users only need to introduce the starter into Maven. Dependency, Spring Boot can automatically scan the information to be loaded and start the corresponding default configuration. The starter provides a large number of automatic configurations, freeing users from the trouble of dealing with various dependencies and configurations. All these starters follow the agreed-upon default configuration and allow users to adjust these configurations, that is, follow the principle of "convention is greater than configuration".

Not all starters are officially provided by Spring Boot, and some starters are provided by third-party technology vendors, such as druid-spring-boot-starter and mybatis-spring-boot-starter, etc. Of course, there are also individual third-party technologies. Spring Boot officially does not provide starters, and third-party technology vendors do not provide starters either.

Taking spring-boot-starter-web as an example, it can provide almost all the dependencies required by the Web development scenario, so when using Spring Boot to develop a Web project, you only need to import the Starter without additionally importing the Web server and other web dependencies.

Introduce spring-boot-starter-web in pom.xml, the sample code is as follows.

<!--SpringBoot父项目依赖管理-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/>
</parent>
....
<dependencies>
    <!--导入 spring-boot-starter-web-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    ...
</dependencies>

Execute the following mvn command in the project to view the dependency tree.
mvn dependency:tree
insert image description here
From the above results, we can see that Spring Boot imports dependencies such as springframework, logging, jackson, and Tomcat, which are exactly what we need when developing web projects.

You may find a problem, that is, in the above pom.xml configuration, when the dependency spring-boot-starter-web is introduced, its version (version) is not specified, but in the dependency tree, we see all dependencies All have version information, so where is the version information controlled? In fact, these version information is uniformly controlled by spring-boot-starter-parent (version arbitration center).

2.2 spring-boot-starter-parent

spring-boot-starter-parent is the parent dependency of all Spring Boot projects. It is called the version arbitration center of Spring Boot, which can manage some common dependencies in the project in a unified manner.

<!--SpringBoot父项目依赖管理-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/>
</parent>

The Spring Boot project can obtain some reasonable default configurations by inheriting spring-boot-starter-parent, which mainly provides the following features:
(1) Default JDK version (Java 8).
(2) The default character set (UTF-8).
(3) Depending on the management function.
(4) Resource filtering.
(5) Default plug-in configuration.
(6) Identify configuration files of type application.properties and application.yml.

1. View the underlying code of spring-boot-starter-parent, and you can find that it has a parent-level dependency spring-boot-dependencies .

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.4.5</version>
</parent>

2. The underlying code of spring-boot-dependencies is as follows .

<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.4.5</version>
<packaging>pom</packaging>
....
<properties>
    <activemq.version>5.16.1</activemq.version>
    <antlr2.version>2.7.7</antlr2.version>
    <appengine-sdk.version>1.9.88</appengine-sdk.version>
    <artemis.version>2.15.0</artemis.version>
    <aspectj.version>1.9.6</aspectj.version>
    <assertj.version>3.18.1</assertj.version>
    <atomikos.version>4.0.6</atomikos.version>
    ....
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-amqp</artifactId>
            <version>${activemq.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-blueprint</artifactId>
            <version>${activemq.version}</version>
        </dependency>
        ...
    </dependencies>
</dependencyManagement>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>${build-helper-maven-plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.flywaydb</groupId>
                <artifactId>flyway-maven-plugin</artifactId>
                <version>${flyway.version}</version>
            </plugin>
            ...
        </plugins>
    </pluginManagement>
</build>

In the above configuration, some elements are described as follows:
(1) dependencyManagement: responsible for managing dependencies;
(2) pluginManagement: responsible for managing plug-ins;
(3) properties: responsible for defining dependencies or version numbers of plug-ins.
spring-boot-dependencies implements unified version management for dependencies or plug-ins of some common technical frameworks through elements such as dependencyManagement, pluginManagement, and properties, such as Activemq, Spring, Tomcat, etc.

2.3 Spring Boot application

The entry point of a Spring Boot Application is the class annotated with @SpringBootApplication. This class should have the main method to run the Spring Boot application. The @SpringBootApplication annotation includes auto-configuration, component scanning, and Spring Boot configuration.
If you add @SpringBootApplication annotation to your class, you don't need to add @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotations. The @SpringBootApplication annotation includes all other annotations.
Note the following code for better understanding

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    
    
   public static void main(String[] args) {
    
    
      SpringApplication.run(DemoApplication.class, args);
   }
}

3 Write a Rest endpoint

To write a simple Hello World Rest endpoint in the Spring Boot Application main class file itself, follow these steps:
(1) First, add @SpringBootApplication and @Controller annotations at the top of the class.
(2) Write the Request URI method using @ResponseBody and @RequestMapping annotations.
(3) The Request URI method should return the Hello World! 123 string.

package net.biancheng.www;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@Controller
public class helloWorldApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(helloWorldApplication.class, args);
    }
    
    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
    
    
        return "Hello World!123";
    }
}

4 configuration files

Writing application.properties in IDEA does not automatically prompt one of the reasons.
When editing the application.properties file, you need to add the Spring Boot plug-in and open it.
The solution is as follows:
1. Click file to select Settings
2. Click Plugins
3. Select Marketplace and search: "Spring Boot" and click Install to install
insert image description here
. Remember to tick the box behind Spring Boot, and then prompt to restart IDEA.
Finally: Check the application.properties file has become a green leaf.
Note: The community version of IDEA cannot install the Spring Boot plugin.

4.1 Basic configuration

Because IDEA is a community version, you cannot install the Spring Boot plug-in, choose to install the Spring Boot Assistant, and then you can use application.yml to identify the configuration content, and finally set it to application.properties.

1、SpringBoot默认配置文件application.properties,通过键值对配置对应属性。
# 服务器端口配置
server.port=80
# 修改banner,logo
spring.main.banner-mode=off
# 修改日志级别
logging.level.root=INFO
2、Spring Boot中导入对应starter后,提供对应配置属性。
3、书写Spring Boot配置采用关键字+提示形式书写。

4.2 Three configuration file types

1、application.properties(传统格式/默认格式,优先级最高)
server.port=80

2、application.yml(主流格式)
server:
    port: 81
    
3、application.yaml(优先级最低)
server:
    port: 82

Guess you like

Origin blog.csdn.net/qq_20466211/article/details/129728201