Spring Boot學習


Spring Boot是為了簡化Spring應用的創建、運行、調試、部署等而出現的,使用它可以做到專注於Spring應用的開發,而無需過多關注XML的配置。

簡單來說,它提供了一堆依賴打包,並已經按照使用習慣解決了依賴問題---習慣大於約定。

 

Spring Boot默認使用tomcat作為服務器,使用logback提供日志記錄。

 

無需多言,直接進入節奏:

 

前提

Spring Boot提供了一系列的依賴包,所以需要構建工具的支持:maven 或 gradle。個人僅熟悉maven,所以下面的內容都是maven相關的。

如果不熟悉maven,請先了解一下。

使用

① 新建一個maven項目。

② pom中parent設為 spring-boot-starter-parent 。建議使用最新的 RELEASE 版本。否則可能需要設置 <repositories/> <pluginRepositories/>

③ 添加應用需要的starter模塊,作為示例,我們僅添加web starter模塊。

  這里需要解釋下starter模塊,簡單的說,就是一系列的依賴包組合。例如web starter模塊,就是包含了Spring Boot預定義的一些Web開發的常用依賴:

○ spring-web, spring-webmvc            Spring WebMvc框架

○ tomcat-embed-*                              內嵌Tomcat容器

○ jackson                                             處理json數據

○ spring-*                                            Spring框架

○ spring-boot-autoconfigure             Spring Boot提供的自動配置功能

  換句話說,當你添加了相應的starter模塊,就相當於添加了相應的所有必須的依賴包。

  starter模塊的列表及含義,見 Spring Boot的啟動器Starter詳解

 

至此,pom內容如下:

<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>cn.larry.spring</groupId>
    <artifactId>larry-spring-demo4</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

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

保存pom,刷新maven,以便刷新依賴導入。
基本上,如果沒有特別的需要,現在就可以直接寫Controller了!!!--特別的需要 是指設置容器、訪問端口、路徑等。后面再解釋。

④ 寫一個簡單的Controller。--直接拿了 Spring Boot——開發新一代Spring Java應用 中的示例。

package cn.larry.spring.controller;

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

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

這里有兩個新東西:@EnableAutoConfigurationSpringApplication

@EnableAutoConfiguration 用於自動配置。簡單的說,它會根據你的pom配置(實際上應該是根據具體的依賴)來判斷這是一個什么應用,並創建相應的環境。

在上面這個例子中,@EnableAutoConfiguration 會判斷出這是一個web應用,所以會創建相應的web環境。

 

SpringApplication 則是用於從main方法啟動Spring應用的類。默認,它會執行以下步驟

  1. 創建一個合適的ApplicationContext實例 (取決於classpath)。
  2. 注冊一個CommandLinePropertySource,以便將命令行參數作為Spring properties。
  3. 刷新application context,加載所有單例beans。
  4. 激活所有CommandLineRunner beans。

默認,直接使用SpringApplication 的靜態方法run()即可。但也可以創建實例,並自行配置需要的設置。

具體的描述見javadoc即可,如下:

Open Declaration org.springframework.boot.SpringApplication


Classes that can be used to bootstrap and launch a Spring application from a Java main method. By default class will perform the following steps to bootstrap your application: 

Create an appropriate ApplicationContext instance (depending on your classpath) 
Register a CommandLinePropertySource to expose command line arguments as Spring properties 
Refresh the application context, loading all singleton beans 
Trigger any CommandLineRunner beans 
In most circumstances the static run(Object, String []) method can be called directly from your main method to bootstrap your application: 
 @Configuration
 @EnableAutoConfiguration
 public class MyApplication  {

 // ... Bean definitions

 public static void main(String[] args) throws Exception {
   SpringApplication.run(MyApplication.class, args);
 }
 
For more advanced configuration a SpringApplication instance can be created and customized before being run: 

 public static void main(String[] args) throws Exception {
   SpringApplication app = new SpringApplication(MyApplication.class);
   // ... customize app settings here
   app.run(args)
 }
 
SpringApplications can read beans from a variety of different sources. It is generally recommended that a single @Configuration class is used to bootstrap your application, however, any of the following sources can also be used: 
Class - A Java class to be loaded by AnnotatedBeanDefinitionReader 
Resource - An XML resource to be loaded by XmlBeanDefinitionReader, or a groovy script to be loaded by GroovyBeanDefinitionReader 
Package - A Java package to be scanned by ClassPathBeanDefinitionScanner 
CharSequence - A class name, resource handle or package name to loaded as appropriate. If the CharSequence cannot be resolved to class and does not resolve to a Resource that exists it will be considered a Package. 
View Code

 

⑤ 現在,直接右鍵啟動main方法即可。啟動信息(包括關閉信息)如下:

 1   .   ____          _            __ _ _
 2  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
 3 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 4  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 5   '  |____| .__|_| |_|_| |_\__, | / / / /
 6  =========|_|==============|___/=/_/_/_/
 7  :: Spring Boot ::        (v1.4.0.RELEASE)
 8 
 9 2016-08-15 14:30:16.565  INFO 10652 --- [           main] c.l.spring.controller.SampleController   : Starting SampleController on Larry with PID 10652 (D:\Workspace\Workspace_sts\larry-spring-demo4\target\classes started by Administrator in D:\Workspace\Workspace_sts\larry-spring-demo4)
10 2016-08-15 14:30:16.567  INFO 10652 --- [           main] c.l.spring.controller.SampleController   : No active profile set, falling back to default profiles: default
11 2016-08-15 14:30:16.596  INFO 10652 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4a94ee4: startup date [Mon Aug 15 14:30:16 CST 2016]; root of context hierarchy
12 2016-08-15 14:30:17.676  INFO 10652 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
13 2016-08-15 14:30:17.687  INFO 10652 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
14 2016-08-15 14:30:17.688  INFO 10652 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.4
15 2016-08-15 14:30:17.767  INFO 10652 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
16 2016-08-15 14:30:17.767  INFO 10652 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1173 ms
17 2016-08-15 14:30:17.928  INFO 10652 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
18 2016-08-15 14:30:17.932  INFO 10652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
19 2016-08-15 14:30:17.933  INFO 10652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
20 2016-08-15 14:30:17.933  INFO 10652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
21 2016-08-15 14:30:17.933  INFO 10652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
22 2016-08-15 14:30:18.177  INFO 10652 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4a94ee4: startup date [Mon Aug 15 14:30:16 CST 2016]; root of context hierarchy
23 2016-08-15 14:30:18.230  INFO 10652 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String cn.larry.spring.controller.SampleController.home()
24 2016-08-15 14:30:18.234  INFO 10652 --- [           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.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
25 2016-08-15 14:30:18.235  INFO 10652 --- [           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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
26 2016-08-15 14:30:18.262  INFO 10652 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
27 2016-08-15 14:30:18.262  INFO 10652 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
28 2016-08-15 14:30:18.295  INFO 10652 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
29 2016-08-15 14:30:18.423  INFO 10652 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
30 2016-08-15 14:30:18.480  INFO 10652 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
31 2016-08-15 14:30:18.485  INFO 10652 --- [           main] c.l.spring.controller.SampleController   : Started SampleController in 2.209 seconds (JVM running for 2.642)
32 2016-08-15 14:30:23.564  INFO 10652 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
33 2016-08-15 14:30:23.564  INFO 10652 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
34 2016-08-15 14:30:23.574  INFO 10652 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 10 ms
35 2016-08-15 14:30:32.002  INFO 10652 --- [2)-192.168.56.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
36 2016-08-15 14:30:32.003  INFO 10652 --- [2)-192.168.56.1] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4a94ee4: startup date [Mon Aug 15 14:30:16 CST 2016]; root of context hierarchy
37 2016-08-15 14:30:32.004  INFO 10652 --- [2)-192.168.56.1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

如果使用sts (Spring Tools Suite--沒意外的話,后面的博客我會介紹一下),還可以用Spring Application的形式啟動,信息不變,但是彩色的,如下:

⑥ 根據這個信息,我們可以看出很多東西,不過現在先訪問一下吧。

默認訪問地址: http://localhost:8080/

按照之前的web項目習慣,你可能會問,怎么沒有項目路徑?

這就是Spring Boot的默認設置了,將項目路徑直接設為根路徑。

當然,我們也可以設置自己的項目路徑 -- 在classpath下的 application.properties 或者 application.yaml 文件中設置即可。

內容如下:

# application.yaml
# Server settings (ServerProperties)
server:
  port: 8080
  address: 127.0.0.1
  sessionTimeout: 30
  contextPath: /aaa

  # Tomcat specifics
  tomcat:
    accessLogEnabled: false
    protocolHeader: x-forwarded-proto
    remoteIpHeader: x-forwarded-for
    basedir:
    backgroundProcessorDelay: 30 # secs
# application.properties
# Server settings (ServerProperties)
server.port=8080
server.address=127.0.0.1
#server.sessionTimeout=30
server.contextPath=/aaa

# Tomcat specifics
#server.tomcat.accessLogEnabled=false
server.tomcat.protocolHeader=x-forwarded-proto
server.tomcat.remoteIpHeader=x-forwarded-for
server.tomcat.basedir=
server.tomcat.backgroundProcessorDelay=30

上面, server.contextPath=/aaa 就是設置了項目路徑。所以現在需要訪問 http://localhost:8080/aaa/ 才行。

 

分析

OK,當目前為止,已經成功運行並訪問了一個 SpringMVC 應用。簡單的不能再簡單了!

再來看一下啟動時的信息:

第 9 行,啟動SampleController。
第10行,查找active profile,無,設為default。
第11行,刷新上下文。
第12行,初始化tomcat,設置端口8080,設置訪問方式為http。
第13行,啟動tomcat服務。
第14行,啟動Servlet引擎。
第15行,Spring內嵌的WebApplicationContext 初始化開始。
第16行,Spring內嵌的WebApplicationContext 初始化完成。
第17行,映射servlet,將 dispatcherServlet 映射到 [/] 。
第18行,映射filter,將 characterEncodingFilter 映射到 [/*] 。
第19行,映射filter,將 hiddenHttpMethodFilter 映射到 [/*] 。
第20行,映射filter,將 httpPutFormContentFilter 映射到 [/*] 。
第21行,映射filter,將 requestContextFilter 映射到 [/*] 。
第22行,查找 @ControllerAdvice。
第23行,映射路徑 "{[/]}" 到 cn.larry.spring.controller.SampleController.home()。
第24行,映射路徑 "{[/error]}" 到 org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)。
第25行,映射路徑 "{[/error],produces=[text/html]}" 到 org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)。
第26行,略。 第27行,略。 第28行,略。 第29行,略。
第30行,tomcat啟動完畢。
第31行,SampleController啟動耗費的時間。
第32行,初始化 dispatcherServlet 。
第33行,dispatcherServlet 的初始化已啟動。
第34行,dispatcherServlet 的初始化已完成。
第35行,收到shutdown關閉請求。
第36行,關閉AnnotationConfigEmbeddedWebApplicationContext。
第37行,略。

從上面的啟動信息中可以明顯看到SpringMVC的加載過程,特別需要注意的是這種默認方式下加載的幾個 filter 。

這里就不再介紹了,具體可以見本文末尾最后三個鏈接。

 

2018.1.8 補充

使用IDEA的Spring Initializer,也可以新建Spring Boot項目,過程類似,不再贅述了。

 

參考:

Spring Boot——開發新一代Spring Java應用
Spring Boot的啟動器Starter詳解
深入學習微框架:Spring Boot
 
Spring MVC過濾器-RequestContextFilter
Spring MVC過濾器-HttpPutFormContentFilter
Spring MVC過濾器-HiddenHttpMethodFilter
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM