Spring Boot 学习01-----搭建一个简单的spring-boot-demo

今天开始要系统性的学习Spring Boot。这个熟悉又陌生的框架,已经陪伴了我2年多。百尺竿头更进一步。

系统环境

构建工具:Maven
spring-boot 1.5.9.RELEASE
JDK 1.8+
Servlet 3.1
Tomcat 8

实施步骤

  1. 新建一个Maven 项目
  2. pom中parent设为 spring-boot-starter-parent 。建议使用最新的 RELEASE 版本,否则可能需要设置 和 。
  3. 添加应用需要的starter,本demo作为演示仅仅添加web模块

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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.jay.springboot</groupId>
  <artifactId>spring-boot-demo-new</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>spring-boot-demo-new Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>

  <!--继承父包-->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
  </parent>
  <dependencies>
    <!--引入web框架-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

  </dependencies>
  <build>
    <finalName>spring-boot-demo-new</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

controller

package com.jay.spring.boot.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 xiang.wei
 * @create 2018/4/2 13:54
 */
@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和SpringApplication。
@EnableAutoConfiguration用于自动配置,它会根据你的pom中具体的依赖来判断这是一个什么应用,并创建相应的环境。
在上面的这个例子中,@EnableAutoConfiguration会判断出这是一个web应用,所以会创建相应的web环境。
SpringApplication 则是用于从main方法启动Spring应用的类。默认,它会执行以下步骤:
1. 创建一个合适的ApplicationContext实例(取决于classpath)
2. 注册一个CommandLinePropertySource,以便将命令行参数作为Spring properties
3. 刷新application context,加载所有单例beans。
4. 激活所有CommandLineRunner beans。

关于SpringApplication类的详解可参考Spring Boot的SpringApplication类详解

说明

默认的访问地址是:http://localhost:8080/
当然我们也可以在classpath下的application.properties或者application.yaml中进行修改。

#application.properties
# Server settings (ServerProperties)
server.port=9191
server.address=127.0.0.1
#server.sessionTimeout=30
server.servlet.context-path=/spring-boot-demo-new

# 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.servlet.context-path=/spring-boot-demo-new就是设置项目路径的,现在需要 http://localhost:9191/spring-boot-demo-new/ 才能访问。
至此,一个最简单的spring-boot的demo就完成了。

启动项目

由于我们使用了spring-boot-starter-parent POM,所以可以使用mvn spring-boot:run 来启动项目
启动之后就可以访问了,地址为:http://localhost:9191/spring-boot-demo-new/

打包

mvn package 用来打包。
注意,Spring Boot的这种打包方式需要使用Spring Boot 提供的spring-boot-maven-plugin

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

注意, spring-boot-maven-plugin POM中包含了<exections> 的配置信息,绑定了repackage goal(maven)。如果你不使用parent POM,你需要自己来声明这个配置信息。
打包完成之后,你可以在/target目录下看到 spring-boot-demo-new.war 这个war包,可以通过 jar tvf target/spring-boot-demo-new.war 来查看其中的内容。
此外,在/target 目录下,还可以看到spring-boot-demo-new.war.original,这是Maven 打包出来的—在Spring Boot repackage之前。

正常执行

正常执行的jar 执行java -jar target/spring-boot-demo-new.war
我们再来回顾下启动日志:

**# 启动SampleController**   
2018-04-02 14:42:16.544  INFO 19536 --- [           main] c.j.s.boot.controller.SampleController   : Starting SampleController on LAPTOP-QF8PE5IK with PID 19536 (D:\Self_learn\spring-boot-demo\spring-boot-demo-new\target\classes started by admin in D:\Self_learn\spring-boot-demo)
**# 查找active profile,无,设为default**
2018-04-02 14:42:16.548  INFO 19536 --- [           main] c.j.s.boot.controller.SampleController   : No active profile set, falling back to default profiles: default
**# 刷新上下文**
2018-04-02 14:42:16.673  INFO 19536 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@52e677af: startup date [Mon Apr 02 14:42:16 CST 2018]; root of context hierarchy
**# 初始化tomcat**
2018-04-02 14:42:19.556 ERROR 19536 --- [           main] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.2.12] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
**# 初始化tomcat服务,设置端口9191 ,访问方式为http**
2018-04-02 14:42:19.964  INFO 19536 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 9191 (http)
2018-04-02 14:42:20.012 ERROR 19536 --- [           main] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.2.12] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
**# 启动tomcat服务**
2018-04-02 14:42:20.040  INFO 19536 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
 **# 启动Servlet引擎**
2018-04-02 14:42:20.040  INFO 19536 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-04-02 14:42:20.067 ERROR 19536 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.2.12] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
**#Spring内嵌的WebApplicationContext初始化开始**
2018-04-02 14:42:20.366  INFO 19536 --- [ost-startStop-1] o.a.c.c.C.[.[.[/spring-boot-demo-new]    : Initializing Spring embedded WebApplicationContext
**#Spring内嵌的WebApplicationContext 初始化完成。**
2018-04-02 14:42:20.367  INFO 19536 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3717 ms
**# 映射servlet,将dispatcherServlet 映射到[/]**
2018-04-02 14:42:20.774  INFO 19536 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
**# 映射filter,将characterEncodingFilter映射到[/*]**
2018-04-02 14:42:20.785  INFO 19536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
**# 映射filter,将hiddenHttpMethodFilter映射到[/*]**
2018-04-02 14:42:20.788  INFO 19536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
**#映射filter,将httpPutFormContentFilter映射到[/*]**
2018-04-02 14:42:20.789  INFO 19536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
**# 映射filter,将requestContextFilter映射到[/*]**
2018-04-02 14:42:20.789  INFO 19536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
**# 查找@ControllerAdvice**
2018-04-02 14:42:21.327  INFO 19536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@52e677af: startup date [Mon Apr 02 14:42:16 CST 2018]; root of context hierarchy
**# 映射路径"{[/]}"到java.lang.String com.jay.spring.boot.controller.SampleController.home()**
2018-04-02 14:42:21.433  INFO 19536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.jay.spring.boot.controller.SampleController.home()
**#映射路径"{[/error]}"到 org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController**
2018-04-02 14:42:21.440  INFO 19536 --- [           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)
**#映射路径 "{[/error],produces=[text/html]}" 到 org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)**
2018-04-02 14:42:21.442  INFO 19536 --- [           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-04-02 14:42:21.489  INFO 19536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-02 14:42:21.489  INFO 19536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-02 14:42:21.528  INFO 19536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-02 14:42:21.762  INFO 19536 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
**#tomcat启动完毕**
2018-04-02 14:42:21.810  INFO 19536 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9191 (http) with context path '/spring-boot-demo-new'
**#SampleController启动耗费的时间。** 
2018-04-02 14:42:21.814  INFO 19536 --- [           main] c.j.s.boot.controller.SampleController   : Started SampleController in 5.722 seconds (JVM running for 6.381)
2018-04-02 14:42:51.657 ERROR 19536 --- [0.1-9191-exec-1] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.2.12] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2018-04-02 14:42:51.663  INFO 19536 --- [0.1-9191-exec-1] o.apache.tomcat.util.http.parser.Cookie  : A cookie header was received [:0.22467848975404947:menuStatus=0,1,0,0,0,0,1; __session:0.6976720437632786:menuStatus=0,1,0,0,0,0,0; Hm_lvt_a68ef7bc907054af4de1f79ec9447c44=1522288869,1522301596,1522391409,1522645861; __session:0.6263519719944086:menuStatus=0,0,0,0,0,0,1; USER.oooooooooooooooo=a5303cad165c5cc5daf5d234202d69842fd4db36127b6055227731fc21c0d9fe28233e61d860c9d0b745b0dfd8426494; Hm_lpvt_a68ef7bc907054af4de1f79ec9447c44=1522647392] that contained an invalid cookie. That cookie will be ignored.Note: further occurrences of this error will be logged at DEBUG level.
**# 初始化dispatcherServlet** 
2018-04-02 14:42:51.677  INFO 19536 --- [0.1-9191-exec-2] o.a.c.c.C.[.[.[/spring-boot-demo-new]    : Initializing Spring FrameworkServlet 'dispatcherServlet'
**#dispatcherServlet 的初始化已启动。**
2018-04-02 14:42:51.678  INFO 19536 --- [0.1-9191-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
**#dispatcherServlet 的初始化已完成。** 
2018-04-02 14:42:51.698  INFO 19536 --- [0.1-9191-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms

附录

相关源码 : https://github.com/XWxiaowei/spring-boot-demo

引用

http://www.cnblogs.com/larryzeal/p/5765945.html

猜你喜欢

转载自blog.csdn.net/u014534808/article/details/79784705