Spring Boot (#1 quick start)

官方文档

Spring Boot是为了简化Spring应用的创建、运行、调试、部署等而出现的,使用它可以做到专注于Spring应用的开发,而无需过多关注XML的配置。

简单来说,它提供了一堆依赖打包,并已经按照使用习惯解决了依赖问题---习惯大于约定。

Spring Boot默认使用tomcat作为服务器,使用logback提供日志记录。

Spring Boot提供了一系列的依赖包,所以需要构建工具的支持:maven 或 gradle

Spring Boot 预定义了一些应用启动器:具体可以见博客Spring Boot的启动器Starter详解

Features

  • 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):

新建一个maven项目

pom中parent设为 spring-boot-starter-parent 。建议使用最新的 RELEASE 版本

添加应用需要的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。

Spring Boot (#1 quick start)的更多相关文章

  1. Spring Boot Admin Quick Start

    Quick Start 1. Spring Boot Admin是干什么的? 用来监控Spring Boot项目,可以通过Spring Boot Admin Client(via Http) 或者 使 ...

  2. [Spring boot] A quick REST API Guide

    Controller: Code below shows a basic Controller to handle GET, POST; DELETE, PUT requests. package h ...

  3. Quick Guide to Microservices with Spring Boot 2.0, Eureka and Spring Cloud

    https://piotrminkowski.wordpress.com/2018/04/26/quick-guide-to-microservices-with-spring-boot-2-0-eu ...

  4. Key Components and Internals of Spring Boot Framework--转

    原文地址:http://www.journaldev.com/7989/key-components-and-internals-of-spring-boot-framework In my prev ...

  5. Spring boot中使用springfox来生成Swagger Specification小结

    Rest接口对应Swagger Specification路径获取办法: 根据location的值获取api   json描述文件 也许有同学会问,为什么搞的这么麻烦,api json描述文件不就是h ...

  6. Enable HTTPS in Spring Boot

    Spring-boot-enable-ssl Enable HTTPS in Spring Boot APRIL 14, 2015DRISS AMRI This weekend I answered ...

  7. Spring boot 内存优化

    转自:https://dzone.com/articles/spring-boot-memory-performance It has sometimes been suggested that Sp ...

  8. spring boot 实践

    二.实践 一些说明: 项目IDE采用Intellij(主要原因在于Intellij颜值完爆Eclipse,谁叫这是一个看脸的时代) 工程依赖管理采用个人比较熟悉的Maven(事实上SpringBoot ...

  9. Spring Boot Memory Performance

    The Performance Zone is brought to you in partnership with New Relic. Quickly learn how to use Docke ...

随机推荐

  1. redmine设置user projects时无法delete的处理方法

    对于user,当要在管理员界面处理其projects权限时,发现部分项目只有edit按钮,而部分项目还有一个delete按钮. “delete”,直接点击按钮即可删除对应project权限,表明该pr ...

  2. C# 泛型类在使用中约束

    首先看一下泛型的基本语法 访问修饰符 返回类型 泛型方法名 <T>(T 参数)   1):无法在泛型方法内部给任何 T 类型创建实例的对象,因为在泛型方法内部不知道传进来的对象有哪些构造函 ...

  3. 关于配置 TeamCity 清理历史 artifacts 问题

    使用 CI 一段时间后,artifacts 占用的磁盘会很大,可以配置保留多少天的 artifacts,具体如下: Administration Click the Edit link for any ...

  4. tomcat关闭后线程依然运行解决办法

    tomcat关闭后线程依然运行解决办法,设置线程为守护线程 守护线程与非守护线程 最近在看多线程的Timer章节,发现运用到了守护线程,感觉Java的基础知识还是需要补充. Java分为两种线程:用户 ...

  5. Web前后端分离知识整理

    Web研发模式的演变 职责分离(减少扯皮,开发效率),代码分离(可维护性) 简单明快的早期时代 后端为主的 MVC 时代 Ajax 带来的 SPA 时代 前端为主的 MV* 时代 Node 带来的全栈 ...

  6. 使用keepalived实现双机热备

    通常说的双机热备是指两台机器都在运行,但并不是两台机器都同时在提供服务.当提供服务的一台出现故障的时候,另外一台会马上自动接管并且提供服务,而且切换的时间非常短.下面来以keepalived结合tom ...

  7. k8s使用nfs动态存储

    1.Kubernetes集群管理员通过提供不同的存储类,可以满足用户不同的服务质量级别.备份策略和任意策略要求的存储需求.动态存储卷供应使用StorageClass进行实现,其允许存储卷按需被创建.如 ...

  8. 【虚拟机ubuntu设置ssh】ssh连不上问题解决方法

    首先,确保server端的ssh服务是开的(service shhd start) 然后在client端输入: ssh usrname@serverip (远程登录) scp filename usr ...

  9. C#调用百度地图API经验分享(二)

    接着上一篇,将上一篇代码的js提取出来:<script type="text/JavaScript">var map = new BMap.Map("allm ...

  10. mysql 中int类型字段unsigned和signed的探索

    转自:http://www.0791quanquan.com/news_keji/topic_816453/ 探索一:正负数问题 拿tinyint字段来举例,unsigned后,字段的取值范围是0-2 ...