Learn Spring Boot

What is Spring Boot?

Simply put, spring boot is a tool for building projects, a scaffolding.

What can Spring boot do?

Spring boot can build production-level monolithic applications with very little configuration.

How does Spring boot do?

Let's make a hello world with spring boot.

  1. Environment preparation, you need to ensure that the following software already exists on your machine

    • JDK1.8 +
    • gradle4+
  2. Create a project directory, assuming this new project is called apple.

    $ cd /tmp
    $ mkdir apple
  3. Create a gradle configuration file and create a build.gradlefile in this directory.

    $ cd apple
    $ vi build.gradle

    Copy the following code into the build.gradlefile.

    plugins {
        id 'org.springframework.boot' version '2.0.1.RELEASE'
    }
    
    apply plugin: 'java'
    apply plugin: 'io.spring.dependency-management'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile 'org.springframework.boot:spring-boot-starter-web'
        testCompile 'org.springframework.boot:spring-boot-starter-test'
        testCompile 'org.springframework.boot:spring-boot-starter-webflux'
    }
    
    bootRun {
        main = 'com.thoughtworks.apple.Launcher'
    }
  4. Write a Hello world.

    • Initialize the project content according to the following directory structure
    apple
      \-src
         \-main
           \-java
              \-com.thoughtworks.apple
                  |-controller
                  |   \-HomeController.java
                  \-Launcher.java              
    • HomeController.java content is as follows
    package com.thoughtworks.apple.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HomeController {
        @RequestMapping("/")
        String home() {
            return "Hello World!";
        }
    }
    
    • The contents of Launcher.java are as follows
    package com.thoughtworks.apple;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.SpringBootConfiguration;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.context.annotation.ComponentScan;
    
    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan("com.thoughtworks.apple")
    public class Launcher {
        public static void main(String[] args) {
            SpringApplication.run(Launcher.class, args);
        }
    }
    
  5. run

    Execute the command to gradle bootRunstart the application, and then the following log will be printed:

    $ gradle bootRun
    
    > Task :bootRun
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.1.RELEASE)
    
    2018-05-05 10:23:41.383  INFO 38941 --- [           main] com.thoughtworks.apple.Launcher          : Starting Launcher on CNyfqi.local with PID 38941 (/private/tmp/apple/build/classes/java/main started by yfqi in /private/tmp/apple)
    2018-05-05 10:23:41.386  INFO 38941 --- [           main] com.thoughtworks.apple.Launcher          : No active profile set, falling back to default profiles: default
    2018-05-05 10:23:41.432  INFO 38941 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3b2c72c2: startup date [Sat May 05 10:23:41 CST 2018]; root of context hierarchy
    2018-05-05 10:23:42.289  INFO 38941 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2018-05-05 10:23:42.313  INFO 38941 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-05-05 10:23:42.313  INFO 38941 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
    2018-05-05 10:23:42.323  INFO 38941 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/yfqi/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
    2018-05-05 10:23:42.402  INFO 38941 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-05-05 10:23:42.403  INFO 38941 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 973 ms
    2018-05-05 10:23:42.522  INFO 38941 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2018-05-05 10:23:42.525  INFO 38941 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-05-05 10:23:42.526  INFO 38941 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-05-05 10:23:42.526  INFO 38941 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-05-05 10:23:42.526  INFO 38941 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-05-05 10:23:42.627  INFO 38941 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-05-05 10:23:42.809  INFO 38941 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3b2c72c2: startup date [Sat May 05 10:23:41 CST 2018]; root of context hierarchy
    2018-05-05 10:23:42.878  INFO 38941 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.thoughtworks.apple.controller.HomeController.home()
    2018-05-05 10:23:42.884  INFO 38941 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2018-05-05 10:23:42.885  INFO 38941 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    2018-05-05 10:23:42.910  INFO 38941 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-05-05 10:23:42.910  INFO 38941 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-05-05 10:23:43.048  INFO 38941 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2018-05-05 10:23:43.100  INFO 38941 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2018-05-05 10:23:43.105  INFO 38941 --- [           main] com.thoughtworks.apple.Launcher          : Started Launcher in 2.148 seconds (JVM running for 2.523)
    2018-05-05 10:24:03.416  INFO 38941 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
    2018-05-05 10:24:03.416  INFO 38941 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
    2018-05-05 10:24:03.436  INFO 38941 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms
    <=========----> 75% EXECUTING [1m 28s]
    > :bootRun

    After visiting in the browser, you http://localhost:8080/can see the following page, indicating that the program runs successfully.

Advanced

How to bring gradle commands into a project

When we have multiple projects locally and the gradle version of each project is different, we need to save the gradle command in the project, and then each project is built with its own gradle. The following command can directly initialize and introduce a gradle command into the project.

$ gradle wrapper --gradle-version 4.0

After that, there will be four more files in the project directory

drwxr-xr-x   4 yfqi  wheel   128 May  5 10:49 .gradle
drwxr-xr-x   3 yfqi  wheel    96 May  5 10:49 gradle
-rwxr-xr-x   1 yfqi  wheel  5296 May  5 10:49 gradlew
-rw-r--r--   1 yfqi  wheel  2260 May  5 10:49 gradlew.bat

Then you can execute it in the project root directory ./gradlewto run gradle tasks.

Test Hello World

The program runs successfully, let's write a test case to test hello world.

  • The test directory structure is as follows

    apple
      \-src
         |-main   
         \-test
            \-java
                \-com.thoughtworks.apple.controller
                   \-HomeControllerTest.java       
  • HomeControllerTest.java content is as follows

    package com.thoughtworks.apple.controller;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.reactive.server.WebTestClient;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class HomeControllerTest {
        @Autowired
        private WebTestClient webClient;
    
        @Test
        public void should_get_home() {
            this.webClient.get().uri("/").exchange()
                    .expectStatus().isOk()
                    .expectBody(String.class).isEqualTo("Hello World!");
        }
    }
  • Run the test and use the command ./gradlew testto see the following log indicating that the test was executed successfully

    $ gradle test
    Starting a Gradle Daemon (subsequent builds will be faster)
    
    > Task :test
    2018-05-05 10:36:18.034  INFO 39291 --- [       Thread-6] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@918accb: startup date [Sat May 05 10:36:15 CST 2018]; root of context hierarchy
    
    
    BUILD SUCCESSFUL in 12s
    3 actionable tasks: 3 executed

Package deployment

  1. Execute the command ./grdlew bootJarto package the spring boot project. After the command is executed successfully, there will apple/build/libsbe an additional jar package apple.jar. This is packaged successfully.
  2. Copy the packaged jar package to the running server, and execute the command java -jar apple.jar &to start the application.

Spring Boot Starters

In the above example, you will find that the project only relies on three Spring Boot Starters to complete the reference to all third-party jar packages. The Starter actually aggregates the dependencies of third-party jar packages according to business needs. Spring Boot provides a large number of The Starter to help developers quickly start building projects, reducing the workload of developers to adjust package dependencies. You can view all Spring Boot Starters at these two addresses.

source code

The full code for the article can be found here: https://github.com/qyf404/learning-spring-boot

About the author

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325338543&siteId=291194637