SpringBoot actual combat learning record

Chapter 1 Getting Started

1.1 Spring learning

1.1.1 Revisit Spring

Suppose you are assigned to develop a simple Hello World Web application with Spring. What to do

1. A project structure, which contains a Maven or Gradle build file that contains necessary dependencies, and at least these dependencies such as Spring MVC and Servlet API.

2. A web.xml file (or a WebApplicationInitializer implementation) in which Spring's DispatcherServlet is declared.

3. A Spring configuration with Spring MVC enabled.

4. A controller class that responds to HTTP requests with "Hello World".

5. A web application server for deploying applications, such as Tomcat.

The most unacceptable thing is that there is only one thing in this list that is related to the Hello World function, that is, the controller, and the rest are common boilerplates necessary for Web applications developed by Spring. Since all Spring Web applications use
them, why do you need to provide these things?

Assume that only the controller is needed here. SpringBoot will do all the logistics of executing the application without configuration, web.xml, build instructions, or even an application server.

1.1.2 Spring Boot Essentials

The four cores of Spring Boot :

  • Automatic configuration : For many common application functions of Spring applications, SpringBoot can automatically provide related configurations.
  • Startup dependency : Tell Spring Boot what functions it needs, and it can introduce the needed libraries.
  • Command line interface : An optional feature of SpringBoot, you only need to write code to complete a complete application, without traditional project construction.
  • Actuator : Allows people to dive into the running Spring Boot application.

1. Automatic configuration

Spring Boot will automatically configure these common configuration scenarios. If Spring Boot finds the H2 database library in the application's Classpath, it will automatically configure an embedded H2 database. If
JdbcTemplate is found in the Classpath, it will also configure a JdbcTemplate Bean for you. You don't need to worry about the configuration of those Beans, Spring Boot will be ready to inject it into your Bean at any time. Spring Boot's automatic configuration is far more than embedded databases and JdbcTemplate, it has a lot of ways to help you reduce the burden of configuration, these automatic configuration involves Java Persistence API (Java Persistence API, JPA), Thymeleaf template, security and Spring MVC.

2. Start-up dependence

Spring Boot provides help for project dependency management through initial dependencies . The initial dependency is actually a special Maven dependency and Gradle dependency. It uses transitive dependency analysis to aggregate common libraries to form several
dependencies customized for specific functions . In short, you import a dependency A, and dependency A will introduce other required dependencies into the project according to the dependency transfer. In addition to reducing the number of dependencies, one dependency can replace a type of dependency, the initial dependency of SpringBoot will also Automatically resolve conflicts caused by version incompatibility.

3. Command line interface

SpringBoot CLI can automatically detect which classes are used in your program and automatically add initial dependencies to the Classpath. This kind of development model is more special than the traditional development model. You only need to write code to realize the application.

4、Actuator

The first three parts of Spring Boot are designed to simplify Spring development, and Actuator provides the ability to view the internal conditions of the application at runtime. Install Actuator to spy on the internal situation of the application, including:

        1) Bean configured in the Spring application context

        2) Decisions made by Spring Boot's automatic configuration

        3) Environment variables, system properties, configuration properties and command line parameters obtained by the application

        4) The current state of threads in the application

        5) Tracking of HTTP requests recently processed by the application

        6) Various indicators related to memory and memory usage, garbage collection, web requests, and data source usage

Actuator provides information to the outside world through Web breakpoints and shell interfaces. If you want to use the shell interface, you can open SSH (Secure Shell), log in to the running application, and send instructions to view its status.

1.2 Getting started with Spring Boot

1.2.1 Use Spring Initializr to initialize Spring Boot project

Spring Initializr is essentially a web application. It can generate Spring Boot project structure for you, provide a basic project organization and Maven or Gradle build instructions for building code.

Several usages of Spring Initializr:

  • Use through the web interface.
  • Use through Spring Tool Suite.
  • Use through IntelliJ IDEA.
  • Use Spring Boot CLI.

1. Use Spring Initializr's web interface

Open http://start.spring.io in your browser to see a page similar to a form. The first two questions of the form are whether to use Maven to build or Gradle to build the project, and which version of Spring Boot to use. On the left side of the form, you need to specify some basic information of the project, such as: Group and Artifact, click on the "Switch to the full version" link, you can also specify additional information, such as version number and basic package name, these information is used to generate Maven's Pom.xml file (or Gradle's build.gradle file).

Dependencies refer to the dependencies that need to be specified in the project. The easiest way is to type the name of the dependency in the text box, and the dependency will be added to the project when selected. Fill out the form, select the dependencies, click the "Generate Project" button, and Spring Initializr will generate a project for you. The browser will be in the form of a ZIP file (the file name depends on the content of the Artifact field). After clicking Generate, a directory like the following will be generated:

                                                                       

In the directory, build.gradle: Gradle build instructions file. If you choose a Maven project, this is Pom.xml.

  • Application.java: A class with a main() method for booting the application.
  • ApplicationTests.java: An empty JUnit test class that loads a Spring application context that uses SpringBoot's automatic configuration function.
  • application.properties: an empty properties file, you can add configuration properties as needed.
  • Static directory: The static content (JavaScript, style sheet, image, etc.) of the web application is placed.
  • templates directory: templates used to present model data.

1.2.2 Create a Spring Boot project in Spring Tool Suite

Stay.

1.2.3 Create a Spring Boot project in IntelliJ IDEA

There are many and simple information on the Internet.

1.2.4 Using Intializr in Spring Boot CLI

Stay.

 Chapter 2 Developing the first application

2.1 Use Spring Boot

First, create a Spring Boot project and get a project structure similar to Figure 2.1:

                                      

2.1.1 View the initialized Spring Boot new project ( initialization )

In Figure 2.1, the entire project structure follows the traditional Maven or Gradle project layout, that is, the main application code is in the src/main/java directory, the resources are in the src/main/resources directory, and the test codes are in src/test/ In the java directory, if any, test resources are placed in src/test/resources.

  • build.gradle: Gradle build instructions file.
  • ReadingListApplication.java: The bootstrap class of the application, which is also the main Spring configuration class.
  • application.properties: Used to configure the properties of the application and Spring Boot.
  • ReadingListApplicationTests.java: A basic integration test class.

Let's first look at ReadingListApplication.java:

1. Start and boot Spring

ReadingListApplication has two functions in Spring Boot applications: configuration and booting. First of all, this is the main Spring configuration class. Although Spring Boot automatically eliminates a lot of Spring configuration, it still requires a small amount of configuration to enable automatic configuration. As shown in code listing 2.1:

@SpringBootApplication turns on Spring's component scanning and Spring Boot's automatic configuration function. In fact, @SpringBootApplication combines three useful annotations.

  • Spring's @Configuration : indicates that this class uses Spring Java-based configuration. This book tends to be based on Java rather than XML configuration.
  • Spring's @ComponentScan : Enable component scanning, so that the web controller classes and other components you write can be automatically discovered and registered for beans in the context of the Spring application.
  • Spring Boot's @EnableAutoConfiguration: This annotation can also be called @Abracadabra-the meaning of a spell, to enable Spring Boot automatic configuration.

In the early version of Spring Boot, these three annotations need to be marked in the ReadingListApplication class at the same time, but starting from Spring Boot 1.2.0, only @SpringBootApplication is required.

ReadingListApplication is also a startup boot class. There are several ways to run Spring Boot applications, including traditional WAR file deployment. But the main() method here can run the application as an executable JAR file on the command line. Here, a reference to the ReadingListApplication class is passed to SpringApplication.run(), along with command line parameters, to start the application through these things.

2. Test the Spring Boot application

Initializr also provides a skeleton of a test class, based on which you can write tests for your application. The test class is not only a placeholder, but also an example, as shown in the code listing 2-2:

A typical Spring integration test uses the @ContextConfiguration annotation to identify how to load the Spring application context. However, in order to give full play to Spring Boot, @SpringApplicationConfiguration annotations should be used here. Just like the code in Listing 2-2, this annotation is used to load the Spring application context from the ReadingListApplication configuration class.

There is also a test method in the test method in Listing 2-2, contextLoads(), which is an empty method, and this empty method is sufficient to prove that the loading of the application context is OK. If the configuration defined in ReadingListApplication is good, it will pass the test. If there is a problem, the test will fail.

3. Configure application properties

Initializr will automatically generate an application.properties file for the project. This file is optional or can be deleted without any impact on the application; in addition, the configuration file can also be fine-grained to adjust SpringBoot automatic configuration.

2.1.2 Analysis of Spring Boot project construction process

Spring Boot provides build plugins for Gradle and Maven to assist in building Spring Boot projects. The code listing 2-3 is the build.gradle file created by Initializr, which applies the Spring Boot Gradle plug-in.

If you use Maven to build the application, Initializr will automatically generate a pom.xml file, which uses the SpringBoot Maven plug-in, as shown in the code listing 2-4:

Whether it's Gradle or Maven, Spring Boot's build plugins help the build process. Gradle's bootRun task can run programs. The Spring Boot Maven plug-in is similar, providing a spring-boot: run goal.

The main function of building the plug-in is to package the project into an executable JAR (uber-JAR), including typing all the dependencies of the application into the JAR file, and adding a description file to the JAR to execute the JAR with java-jar.

In addition to building plug-ins, the Maven build instructions in Listing 2-4 also use spring-boot-starter-parent as the upper level, so that you can use Maven's dependency management function, inherit the dependency versions of many commonly used libraries, and declare dependencies again There is no need to specify the version number anymore. Note: No version is specified in the pom.xml here.

2.2 Use initial dependencies

If there is no initial dependency, even if you are developing a simple Spring Web program, you still need Thymeleaf view, data persistence through JPA, etc. And there are various issues such as version compatibility. The initial dependence of Spring Boot is to solve these problems.

2.2.1 Specify feature-based dependencies

Spring Boot reduces the complexity of project dependencies by providing numerous initial dependencies. The initial dependency is essentially a Maven project object model (Project Object Model, POM), which defines transitive dependencies on other libraries. Together, these things support a certain function. The names of many start-up reliances imply some or a certain kind of function they provide. For example, if you plan to make a certain program into a Web program, just add Spring Boot's Web start-up dependency directly. The easiest way to add these dependencies is to select the Web, Thymeleaf, and JPA checkboxes in Initializr. Through transitive dependencies, adding dependencies is equivalent to adding a lot of independent libraries. These transitive dependencies cover Spring MVC, Spring Data JPA, Thymeleaf, etc., and their declared dependencies will also be passed in. Appendix B lists all the initial dependencies and briefly describes what they introduce into the project.

The initial dependency will be determined by the SPring Boot version and the version of the transitive dependency. So we do not need to specify a version number, but if you want to know the version number, the use of dependency in Maven plug-in tree goal will significantly show a dependency tree, each containing a library and version used by the project. $mvn dependency:tree

In most cases, it does not need to be related to what each Spring Boot start-up dependency declares separately. Web start-up relies on being able to build web applications, Thymeleaf start-up reliance on being able to use Thymeleaf templates, and Spring Data JPA starting-up reliance on being able to make data persist in the database. However, if there is a problem with the selected library for the initial dependency, how to override the initial dependency?

2.2.2 Override the transitive dependency introduced by the initial dependency

The start-up dependencies are no different from other dependencies in the project. You can selectively override the version numbers of the transitive dependencies they introduce through the function of the build tool, exclude transitive dependencies, and specify dependencies for libraries that are not covered by the Spring Boot start-up dependencies. Take the Web start-up dependency as an example. It transitively relies on the Jaskson JSON library. Generally, if you don't need Jackson to build web applications for human users, you can eliminate its transitive dependency and slim down the project. as follows:

In Gradle, the way to exclude dependencies: Omitted. In Maven, you can use the <exclusions> element to exclude transitive dependencies:

Maven will always use the most recent dependency, and this dependency added in the project build specification file will override another dependency introduced by the transitive dependency.

2.3 Use automatic configuration

Spring Boot's automatic configuration is a process at runtime (more precisely, when the application starts). Many factors are considered to determine which Spring configuration should be used and which should not be used.

2.3.1 Focus on application features

    1. Define the domain model

The core domain concept in our application is the book on the reader reading list. Therefore, we need to define an entity class to represent this concept. Listing 2-5 demonstrates how to define a book.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String reader;
private String isbn;
private String title;
private String author;
private String description;
public Long getId(){
    return id;
}
public void setId(Long id){
    this.id = id;
}
......

As you can see, the Book class is a simple Java object, some of which describe the properties of the book, as well as necessary access methods. The @Entity annotation indicates that it is a JPA entity. The id attribute is annotated with @Id and @GeneratedValue, indicating that this field
is the unique identifier of the entity, and the value of this field is automatically generated.

2. Define the warehouse interface

Next, we are going to define the warehouse used to persist Book objects to the database. Because Spring Data JPA is used, all we have to do is to simply define an interface to extend the JpaRepository interface of Spring Data JPA:

import com.example.springboottest.springboottest.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ReadingListRepository extends JpaRepository<Book,Long> {
    List<Book> findByReader(String reader);
}

By extending JpaRepository, ReadingListRepository directly inherits 18 methods of performing common persistence operations. JpaRepository is a generic interface with two parameters: the type of the domain object of the warehouse operation and the type of its ID attribute
. In addition, a findByReader() method has been added here, which can search the reading list according to the user name of the reader. If you are curious about who will implement this ReadingListRepository and the 18 inherited methods, don't worry,
Spring Data provides a magical magic. You only need to define the warehouse interface. After the application is started, the interface will be automatically implemented at runtime.

3. Create a web interface

Now that we have defined the domain model of the application, and the warehouse interface to persist the domain objects in the database, the rest is to create the Web front end. The Spring MVC controller in Listing 2-6 can handle HTTP requests for the application.
 

package com.example.springboottest.springboottest.controller;

import com.example.springboottest.springboottest.entity.Book;
import com.example.springboottest.springboottest.service.ReadingListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;


import java.util.List;



@Controller
@RequestMapping("/")
public class ReadingListController {

    private ReadingListRepository readingListRepository;

    @Autowired
    public ReadingListController(ReadingListRepository readingListRepository){
        this.readingListRepository = readingListRepository;
    }

    @RequestMapping(value = "/{reader}",method = RequestMethod.GET)
    public String readerBooks(@PathVariable("reader") String reader, Model model){
        List<Book> readingList = readingListRepository.findByReader(reader);
        if(readingList != null){
            model.addAttribute("books",readingList);
        }
        return "readingList";
    }

    @RequestMapping(value = "/{reader}",method = RequestMethod.POST)
    public String addToReadingList(@PathVariable("reader") String reader,Book book){
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/{reader}";
    }
}

ReadingListController uses the @Controller annotation, so that component scanning will automatically register it as a Bean in the Spring application context. It also uses the @RequestMapping annotation, which maps all the handler methods to the URL path "/". The controller has two methods:

  • readersBooks(): Process the HTTP GET request on /{reader}, and get the book list from the warehouse (injected through the controller's constructor) according to the reader specified in the path. This list is then stuffed into the model, the key used is books, and finally readingList is returned as the logical name of the view of the presentation model.
  • addToReadingList(): Process the HTTP POST request on /{reader}, and bind the data in the request body to a Book object. This method sets the reader property of the Book object to the name of the reader, then saves the modified Book object through the save() method of the warehouse, and finally redirects to /{reader} (another method in the controller will handle the request) .

The readersBooks() method finally returns readingList as the logical view name, for which the view must be created. Because at the beginning of the project I decided to use Thymeleaf to define the view of the application, so next I created a file named readingList.html in src/main/resources/templates, as shown in code listing 2-7 Show.
 

Guess you like

Origin blog.csdn.net/VABTC/article/details/109581225