Chapter 1: Introduction to Spring Boot2

1. Learning requirements

  • Familiar with Spring basics
  • Familiar with Maven

2. Environmental requirements

Java8 and above

Maven 3.5 and above

IO /spring-boot…

Official: Spring Boot 2.6.4 requires Java 8 and is compatible up to and including Java 17.Spring Framework 5.3.16 or above is also required.

Explicit build support is provided for the following build tools:

Build Tool Version
Maven 3.5 +
Gradle 6.8 x, 6.9 x, and 7. X

3. Spring and SpringBoot

3.1 What can Spring do

When Java and Java-Web developers mention Spring, the first words that come to mind are “IOC”, “AOP”, “Spring MVC”, “Spring Security” and so on, and even “Java without Spring”. In fact, Spring is no longer a simple programming framework. From the original “SSH framework” to today, Struts and Hibernate have almost disappeared from the sight of programmers, while Spring has developed into a very large and complete ecosystem.

So, unless specifically referring to a specific framework within the Spring ecosystem, “Spring” should refer to the entire Spring ecosystem. It is no exaggeration to say that Java programmers who have mastered Spring have mastered the essence of Java development.

There are many specific frameworks that can be used in specific scenarios throughout the Spring ecosystem, such as: “Spring Framework”, “Spring Security”, “Spring Boot”, “Spring Cloud” and so on, among which the “Spring Framework” Framework is the core foundation of the whole ecosystem, Other frameworks rely on basic functions provided by the Spring Framework, and each Framework has its own repository of code.

IO/Spring can implement… They are microservices, responsive programming, cloud services, Web applications, no services, event-driven, and batch.

3.2 Spring’s ecosystem

Projects in the Spring ecosystem fall into three categories: Main Projects, Community Projects, and Projects in the Attic that have been terminated. Covered: Web development, data access, security control, distribution, messaging services, mobile development, batch processing,……

For an updated list of Spring ecosystem projects, see Spring. IO /projects

IO /projects/sp…

3.3. Why SpringBoot?

Spring Boot makes it easy to create standalone, production-grade Spring based Applications that you can “just run”.

The ability to quickly create production-grade Spring applications

Let’s put it in more colloquial terms: If we completely use Spring ecology to develop an advanced project, first of all, in terms of data access, we need to learn some knowledge in SpringDate and do the corresponding configuration, and then we need to learn and configure other things in Spring ecology to complete the development of the whole project. Therefore, when using this traditional Spring to develop, even a simple JavaEE (Java Enterprise Edition) development, there are a large number of XML files in the project, resulting in the JavaEE project becomes gradually bulky, cumbersome configuration and integration of third-party framework configuration. This leads to reduced development and deployment efficiency, not to mention more advanced projects.

How can you simplify the way out of this configuration hell form of development? SpringBoot appeared

Spring Boot is not a solution to replace Spring, but rather a tool that works closely with the many frameworks in the Spring ecosystem to enhance the Spring developer experience. It also integrates a large number of common third-party library configurations. These third-party libraries can be almost out-of-the-box for Spring Boot applications. Most Spring Boot applications require very little configuration code (Java-based configuration). Developers can focus more on business logic.

One of the biggest benefits of using SpringBoot is simplified configuration, which is automated.

3.4. Major upgrade of Spring5

1. Upgrade of Spring5, SpringBoot has also been upgraded to version 2, introducing a responsive programming Reactor

2, internal source design: Java8 based on some new features, such as: interface default method implementation. Redesign the source code architecture. Address some issues with Spring’s adapter pattern

3.5. SpringBoot advantages

  • Create standalone Spring Applications: Create a standalone Spring application
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files) Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated ‘starter’ dependencies to simplify your build configuration: The automatic starter dependency simplifies construction and configuration, and controls jar dependencies. You only need to import the starter scenario. Other dependencies are automatically imported, for example, you only need to import the Web starter
  • Automatically configure Spring and 3rd party libraries whenever possible: Automatically configure Spring and 3rd party libraries whenever possible
  • Provide production-ready features such as metrics, health checks, and externalized configuration: Provide production-level monitoring, health checks, and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration: There is Absolutely no code generation and no XML configuration is required

Conclusion:

  • SpringBoot is a one-stop framework for integrating Spring technology stacks
  • SpringBoot is a rapid development scaffolding that simplifies the Spring technology stack

3.6 disadvantages of SpringBoot

  • Known as version emperor, iteration fast, need to pay attention to change
  • The package is too deep and the internal principle is complex, which is not easy to master. The underlying principle is the Spring framework

4. Historical background

4.1. Microservices

James Lewis and Martin Fowler (2014) put forward the complete concept of microservices. Martinfowler.com/microservic…

In short, the microservice architectural style is an approach to developing a single application as a suite of small services , each running in its own process and communicating with **lightweight mechanisms, often an **HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.— James Lewis and Martin Fowler (2014)

Translation Summary:

  1. Microservices is an architectural style, see SpringCloud
  2. An application is split into a set of small services
  3. Each service runs within its own process, which means it can be deployed and upgraded independently
  4. Services interact with each other using lightweight HTTP
  5. Services are split around business functions
  6. It can be independently deployed by the automatic deployment mechanism
  7. Decentralization, service autonomy. Services can use different languages and storage technologies
  8. The rise of microservices must refer to the application of distributed systems

Past monolithic application architectures

The so-called all in One application architecture is the value. We encapsulate all the application services in an application into one application. Whether it is ERP, CRM or other systems, you have database access, Web access… And so on into a WAR package

The advantage of a single application is that it is easy to develop and test, and it is also very convenient to deploy. When you need to expand, you only need to copy multiple copies of the WAR package, put it on multiple servers, and perform load balancing

The disadvantage of single application is that if we modify a very small place, we need to stop the whole service, repackage and deploy the application WAR package, especially for a large application, we cannot put all the content in one application, how to maintain and how to work with others is a problem

Microservices Architecture

So-called micro service architecture is broken before all in one way of architecture, the elements of each functional independence, the independence of the functional elements of the dynamic combination, need functional elements to bring combination, need more functional elements can integrate multiple functional elements, so the micro service architecture is to copy of functional elements, Instead of copying the entire application

The benefit of the microservice architecture is that the invocation resources are saved, and the service of each functional element is a replaceable, independently upgradable software code

How do you build microservices

The microservice architecture of a large system is like a complex interwoven neural network, in which each neuron is a functional element, each of which performs its own function and then requests and calls each other through HTTP. Such as an electricity system, check the cache, even the database and browse pages, invoicing, payment and other services are the function of the individual services, were slightly as a service, as with service jointly built a huge system, if you change one of the function, only need to update the upgrade service units can be one of the function.

However, such a huge system architecture brings great difficulties to deployment and operation. Therefore, Spring brings us a complete and whole-process product for building large distributed micro-services:

  • Build a functional independent microservice application unit, can use SpringBoot, can help us quickly build an application
  • The invocation of large distributed network services, which is done by springcloud, is distributed
  • In the distributed middle, for streaming data computing and batch processing, we have Spring Cloud Data Flow
  • Spring has figured out the whole process for us, from building an application to a large distributed application

4.2 Distributed

4.2.1 Distributed difficulties

It’s all explained in SpringCloud

  • The remote invocation
  • Service discovery
  • Load balancing
  • Service fault tolerance
  • Configuration management
  • Service monitoring
  • Link to track
  • Log management
  • Task scheduling
  • .

4.2.2 Distributed solution

SpringBoot + SpringCloud

4.3 Cloud Yuansheng

How do Native apps go to Cloud: Cloud Native

4.3.1 Difficulties in getting on the cloud

  • Service self-healing
  • Elastic scaling
  • Service isolation
  • Automated deployment
  • Gray released
  • Traffic management
  • .

4.3.2 Solution of upper cloud

5. How to learn SpringBoot

5.1、Spring Boot Reference Documentation

  • Reference: docs. Spring. IO/spring – the boot…
  • Spring Boot 2.5.3 API: docs. Spring. IO /spring-boot…
  • To view the published log version: spring. IO /projects/sp…
  • View new version features. Github.com/spring-proj…

6, summary

Spring Boo is a lightweight application framework designed to simplify the initial setup and development of Spring applications. In addition, By integrating a large number of frameworks, SpringBoot solves the problems of dependency package version conflicts and reference instability.

Features:

You can create standalone Spring applications and create executable JARs and WARs based on their Maven or Gradle plug-ins. 2. Embedded Servlet containers such as Tomcat or Jetty.

3. Provide automatic configuration of the “Starter” project object model (POMS) to simplify Maven configuration.

Automatically configure the Spring container without XML configuration

Chapter 2: Getting Started with Spring Boot2

Official address: docs.spring. IO /spring-boot…

1, Maven Settings [setting. XML global configuration file]

<mirror>
    <id>nexus-aliyun</id>
    <mirrorOf>central</mirrorOf>
    <name>Nexus aliyun</name>
    <url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>

<profile>
    <id>JDK - 1.8 -</id>
    <activation>
        <activeByDefault>true</activeByDefault>
        <jdk>1.8</jdk>
    </activation>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>
</profile>
</profiles>
Copy the code

In this way, there is no need to modify the project poM file separately, once and for all, it is better to copy the original setting.xml file

Create the HelloWorld-Maven project

Requirement: browse send/helloRequest, response: Hello, Spring Boot 2

2.1. Create POM

Create the Maven project and introduce SpringBoot’s JAR configuration dependencies in POM.xml

  • A parent project is used to specify version 2.6.4 for all dependencies related to the SpringBoot framework
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.4</version>
</parent>
Copy the code

2.3. Add classpath dependencies

Spring Boot provides a number of “initiators” that let you add jars to your classpath, and since we’re developing a Web application, we added a Spring-boot-starter-Web dependency, Introduction of springboot-Web scenario development dependencies [parent project specified, version not required]

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
Copy the code

2.4. Add the Main method of SpringBoot to start the class

Use SRC -> main -> Java to create a new MainApplication class and comment @springBootApplication to tell SpringBoot this is a SpringBoot application. Write the main method to let the Spring application run the main class.

package com.lemon.boot;

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

/ * * *@Author Lemons
 * @createThe 2022-03-07-10:53 * /

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

Notes:

  • @springBootConfiguration: Specifies that this class belongs to a configuration class
  • EnableAutoConfiguration: This annotation tells Spring Boot to “guess” how you configure Spring based on the JAR dependencies you added. This is equivalent to automatically starting Spring based on configuration.
  • @ComponentScan: Specifies the package to be scanned when the application is started. The default is to scan the current package and its subpackages.
  • @SpringBootApplication: A default common annotation that replaces the previous three annotations and can be used when using the SpringBoot default configuration.

2.5. Write business logic

Create a Controller class, annotating @Controller as shown above, and write a method that handles the Hello request and returns @responseBody as a string. Since the Controller class handles a lot of requests (methods) that may return information to the browser, putting @responseBody directly at the top of the class means that every method in our class returns data directly to the browser, rather than jumping to a page.

@Controller
@ResponseBody
public class HelloController {
    @RequestMapping("/hello") //1. Request mapping
    public String hand01(a) {
        return "Hello World!"; }}Copy the code

2. @responseBody and @Controller can be replaced by @restController, because @restController is a combination of both.

@RestController  // automatic assembly
public class HelloController {
    @RequestMapping("/hello")
    public String hand01(a) {
        return "Hello World!"; }}Copy the code

Notes:

The @requestMapping annotation provides routing information. It tells Spring that any HTTP request with the/path should be mapped to the hand01 method. The annotation tells Spring to render the @RestController result string directly to the caller.

@Controller: Indicates that the class is a Controller, a branch of the @Component annotation, which further reflects the scope of the class.

ResponseBody: This annotation tells Spring to return the resulting string directly to the caller.

@restController: This annotation is a combination of the @Controller and @responseBody annotations to replace the two annotations. However, there are some scenarios where this annotation cannot be used between methods, such as when a method needs to be redirected. It is used to jump to third-party systems.

2.5, tests,

Startup steps:

Through the run method, first obtain the Main method of SpringBoot as the startup entrance, read the configuration file, and then register the corresponding bean, such as the package to be scanned, the Servlet to be loaded, and then load the application server to be started, such as Tomcat, and publish the application program.

Simply run the start class method

____ ____ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | | | (_ | |))))' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.4) 11:01:35 2022-03-07. 18076-255 the INFO [main] com. Lemon. The boot. MainApplication: Starting MainApplication using Java 1.8.0_131 on laptop-du0LC6fo with PID 18076 (E:\ springboot-01 \target\classes started By lemon in E: \ SpringBoot 11:01:35 2022-03-07-01), 18076-262 the INFO [main] com. Lemon. The boot. MainApplication: No active profile set, falling back to 1 default profile: "Default" is the 2022-03-07 11:01:36. 18076-265 the INFO [main] O.S.B.W.E mbedded. Tomcat. TomcatWebServer: Tomcat initialized with port(s): 8080 (HTTP) 11:01:36 2022-03-07. 18076-276 the INFO [main] o.a pache, catalina. Core. StandardService: Starting the service [Tomcat] 2022-03-07 11:01:36. 276 INFO 18076 - [the main] org. Apache. Catalina. Core. StandardEngine: Starting Servlet engine: [Apache Tomcat/9.0.58] 2022-03-07 11:01:36.371 INFO 18076 -- [main] O.A.C.C.C. [Tomcat].[/] : Initializing Spring Embedded WebApplicationContext 2022-03-07 11:01:36.372 INFO 18076 -- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: Initialization Completed in 1024 MS 2022-03-07 11:01:36.745 INFO 18076 -- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''18076-2022-03-07 11:01:36. 755 INFO [main] com. Lemon. The boot. The MainApplication: Started MainApplication in 2.255 seconds (JVM running for 4.175)Copy the code

The browser enters the API address: localhost:8080/hello. The web page responds with Hello, world. successful

Doesn’t it feel a little easy? Yes, we don’t need to configure any servers or anything, because Springboot does it for us.

3. Simplify SpringBoot configuration

All SpringBoot configurations can be written in a configuration file; Right click on Resources and create a new file with the fixed name application.properties.

Configuring server Ports

For example, you can change the port number of the TomCat server in this configuration file: you can simplify the configuration without having to change the number of configuration files in the respective conf directory.

server.port=8888
Copy the code

Browser: localhost:8080/hello returns Hello, world. successful

If we configure Mybatis, we can also configure MySQL database data source, password and other resource information, so the configuration file can write what? Refer to the official documentation Application Properties: Core Properties for various types of configurations:

[docs. Spring. IO/spring – the boot…

Configure the banner

There are several ways:

  • Can inapplication.ymlorapplication.propertiesIn the injectionbanner.locationAnd place the custom graphics file in this directory

  • Directly in the root configuration file directorybanner.txtFile, because that’s the fixed name
    • In the projectresourcesCreating a Directorybanner.txtAnd write the following text

4. Create an Executable Jar

Create an executable Jar package, that is, we just need to import the plug-in provided by Spring Boot, we can package the Web project directly into a Jar package, and do not need to specify the WAR package in the PACKAGE of poM file, and then deploy it to the server. This executable Jar contains the runtime environment for our entire project, often referred to as FAT jars.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
Copy the code

Save pum. XML and run MVN package from the command line to execute the package operation. Of course, IDEA automatically provides Maven options.

Packing done:

Enter the Target directory to view the packaged project

In this directory: Go to CMD to view the dir command

Of course, you can also use the following command to view the contents of the project

$jar TVF target/ project name.jarCopy the code

The jar package can be executed directly by entering Java -jar springboot-01-1.0-snapshot.jar on the command line

Access localhost:8888/hello and find that it is accessible again, simplifying deployment on the server.

5. The project structure diagram is as follows

Section three: Developing tips

1, Lombok

To simplify JavaBean development: in the past to write class attributes get/set/toString methods, trouble [caution]

1. Install lombok plugin in IDEA search [new version already integrates this plugin]

2. Pom files introduce Lombok dependencies and IDEA automatically manages versions for us

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
Copy the code

3. Direct program use, as follows

/ / = = = = = = = = = = = = = = = = = = = simplify JavaBean development = = = = = = = = = = = = = = = = = = =
@NoArgsConstructor // No parameter constructor
// @a1largsconstructor uses all the attributes of the class to generate the parameterised constructor
@Data  // Lombok's annotations help us generate get/set methods for existing attributes
@ToString // Lombok's annotations help us generate the toString method
@EqualsAndHashCode // Override HashCode and Equals methods
public class User {
    private String name ;
    private Integer age;
    private Pet pet ;

    // Comment out @allargsconstructor when you don't want a full-argument constructor and write your own
    public User(String name , Integer age){
        this.name = name;
        this.age = age; }}//=================== Simplified log printing ===================

@Slf4j // Use sysout to print logs
@RestController
public class HelloController{
    @RequestMapping("/hello")
    public String handle01 (@RequestParam("name") String name){
        log.info("Request comes in....");
        return "Hello, Spring Boot 2!" + "Hello."+ name; }}Copy the code

2. Dev-tools [hot deployment]

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
Copy the code

After project or page modification: Ctrl+F9 to recompile the project; It takes effect in real time. No need to restart the project.

3. Use Spring Initializr to quickly build the project

This is the most important: the previous project development scenario will introduce what scene dependency, but also reference documents, and then create maven project to introduce dependency, it is too troublesome, before this, we mainly through Maven Archetype to quickly generate Maven project, project prototype is relatively simple, the support for various IDE is not too friendly. However, using Spring Initializr to build Maven projects, it not only perfectly supports IDEA and Eclipse, but also automatically generates startup classes and unit test code, bringing great convenience to developers!!

1. Create a new project and go to Spring Initailizr (Project initialization Wizard)

In IDEA select File -> New -> Project -> Spring Initializr -> Next.

Fill in the organization information, project name, package type select Jar, and click Next.

2. Choose the development scenario we want

For example, to select a Web scenario, here we select Web dependency and click Next. Then check the project name and project path and select Finish.

After the creation of automatic dependency introduction, check the POM file as follows: Introduction of The Web scenario, Mybatis scenario, unit test scenario, packaged plug-in are introduced

3. After creating the project structure

4, automatically write the main program class and test class

Automatically write the main program class, only need to write dao/service/controller, only need to care about business development, and the test package also automatically generated unit test classes for us

This class cannot be deleted or changed. The storage DAO interface, storage Service interface and its implementation class, as well as the DAO, Service, and Controller package we want to create must be at the same level as the main class, otherwise the project cannot work properly, because the regulation is that the project cannot be identified if it does not follow the convention, and the convention is greater than the configuration. The application.properties file is the core Springboot configuration file, but we usually use yamL configuration files. The test directory has a default test class for testing

Run the main method directly, you can see the information of Tomcat startup, we directly enter localhost:8080 press enter, get the following page, default jump to a static page of /error

Mysql database: mybatis (mybatis)

So what can this configuration file write? Refer to the official documentation Application Properties: Core Properties for various types of configurations:

Docs. Spring. IO/spring – the boot…