Spring Boot (#1 quick start)

Spring Boot (#1 quick start)

官方文檔html

Spring Boot是爲了簡化Spring應用的建立、運行、調試、部署等而出現的,使用它能夠作到專一於Spring應用的開發,而無需過多關注XML的配置。java

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

Spring Boot默認使用tomcat做爲服務器,使用logback提供日誌記錄。github

Spring Boot提供了一系列的依賴包,因此須要構建工具的支持:maven 或 gradleweb

Spring Boot 預約義了一些應用啓動器:具體能夠見博客Spring Boot的啓動器Starter詳解spring

Featuresapache

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated 'starter' POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration

quick start

以官網quick start 爲例(maven):tomcat

新建一個maven項目

pom中parent設爲 spring-boot-starter-parent 。建議使用最新的 RELEASE 版本springboot

添加應用須要的starter模塊,做爲示例,咱們僅添加web starter應用啓動器。web starter應用啓動器包含了一系列依賴包組合,如spring-web,spring-webmvc,tomcat-embed-,jackson,spring-,spring-boot-autoconfigure。服務器

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>cn.ifengkou</groupId>
    <artifactId>spring-boot-test</artifactId>
    <version>1.0</version>

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

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

</project>

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;

/**
 * 描述
 *
 * @author shenlongguang<https://github.com/ifengkou>
 * @date 2017/4/11 17:43
 */
@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);
    }
}

@EnableAutoConfiguration,用於自動配置,它會根據你的pom配置(實際上應該是根據具體的依賴)來判斷這是一個什麼應用,並建立相應的環境
SpringApplication 啓動步驟

  1. 建立一個合適的ApplicationContext實例 (取決於classpath)。
  2. 註冊一個CommandLinePropertySource,以便將命令行參數做爲Spring properties。
  3. 刷新application context,加載全部單例beans。
  4. 激活全部CommandLineRunner beans。

3 啓動 訪問

直接運行main方法直接啓動

...... 一次完成的啓動見後面的分析
2017-04-11 18:46:54.255  INFO 4868 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-04-11 18:46:54.307  INFO 4868 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-04-11 18:46:54.311  INFO 4868 --- [           main] c.i.s.controller.SampleController        : Started SampleController in 2.585 seconds (JVM running for 3.044)

直接訪問 localhost:8080 就能夠看到頁面輸出 hello world

配置

在classpath下的 application.properties 或者 application.yaml 文件中設置便可

好比更改端口號,變動項目路徑,例以下面的配置就須要 localhost:8080/springboot才能訪問

application.yaml

# Server settings (ServerProperties)
server:
  port: 8080
  address: 127.0.0.1
  sessionTimeout: 30
  contextPath: /springboot

  # 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

啓動步驟分析

[           main] c.i.s.controller.SampleController        : Starting SampleController on SC-201603222017 with PID 4868 (E:\workspace\spring-boot-test\target\classes started by Administrator in E:\workspace\spring-boot-test)
[           main] c.i.s.controller.SampleController        : No active profile set, falling back to default profiles: default
[           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d5620ce: startup date [Tue Apr 11 18:46:52 CST 2017]; root of context hierarchy
[           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
[           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
[           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
[ost-startStop-1] o.a.c.c.C.[.[localhost].[/springboot]    : Initializing Spring embedded WebApplicationContext
[ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1377 ms
[ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
[ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
[ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
[ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
[ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
[           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d5620ce: startup date [Tue Apr 11 18:46:52 CST 2017]; root of context hierarchy
[           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String cn.ifengkou.springboot.controller.SampleController.home()
[           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)
[           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)
[           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
[           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
[           main] c.i.s.controller.SampleController        : Started SampleController in 2.585 seconds (JVM running for 3.044)
[0.1-8080-exec-3] o.a.c.c.C.[.[localhost].[/springboot]    : Initializing Spring FrameworkServlet 'dispatcherServlet'
[0.1-8080-exec-3] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
[0.1-8080-exec-3] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms
  • 啓動SampleController。
  • 查找active profile,無,設爲default。
  • 刷新上下文。
  • 初始化tomcat,設置端口8080,設置訪問方式爲http。
  • 啓動tomcat服務。
  • 啓動Servlet引擎。
  • Spring內嵌的WebApplicationContext 初始化開始。
  • Spring內嵌的WebApplicationContext 初始化完成。
  • 映射servlet,將 dispatcherServlet 映射到 [/] 。
  • 映射filter,將 characterEncodingFilter 映射到 [/*] 。
  • 映射filter,將 hiddenHttpMethodFilter 映射到 [/*] 。
  • 映射filter,將 httpPutFormContentFilter 映射到 [/*] 。
  • 映射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)。
  • tomcat啓動完畢。
  • SampleController啓動耗費的時間。
  • 初始化 dispatcherServlet 。
  • dispatcherServlet 的初始化已啓動。
  • dispatcherServlet 的初始化已完成。
  • 收到shutdown關閉請求。
  • 關閉AnnotationConfigEmbeddedWebApplicationContext。
相關文章
相關標籤/搜索