Spring Boot 官方文档摘要

一、Develop Your First Spring Boot Application

Spring Boot 依赖于 groupIdorg.springframework.boot 的组件。一般来说都是依赖 spring-boot-starter-parent 组件,也可以根据需要添加更多的 Starter

以下是pom文件的配置:

<?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>com.example</groupId><artifactId>myproject</artifactId><version>0.0.1-SNAPSHOT</version><!-- Inherit defaults from Spring Boot --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.0.M3</version></parent><!-- Add dependencies --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-properties-migrator</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><!-- (you don't need this if you are using a .RELEASE version) --><repositories><repository><id>spring-snapshots</id><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</enabled></snapshots></repository><repository><id>spring-milestones</id><url>https://repo.spring.io/milestone</url></repository></repositories><pluginRepositories><pluginRepository><id>spring-snapshots</id><url>https://repo.spring.io/snapshot</url></pluginRepository><pluginRepository><id>spring-milestones</id><url>https://repo.spring.io/milestone</url></pluginRepository></pluginRepositories>
<project/>

mvn denpendency:tree会打印并以树形展示项目依赖

1. Maven

Maven用户可以继承spring-boot-starter-parent工程来获得合理的默认配置。父工程提供了下面的特性:

  • Java 1.6作为默认的编译级别。
  • UTF-8源码编码。
  • 依赖管理部分,对于常用的依赖允许你忽略``标签,从spring-boot-dependencies继承POM。
  • 合理的资源过滤。
  • 合理的插件配置(exec plugin, surefire, Git commit ID, shade)。
  • 对包括特定配置文件的application.propertiesapplication.yml的合理资源过滤(例如,application-foo.propertiesapplication-foo.yml)。

由于默认配置文件采用Spring风格的占位符(${…}),Maven过滤改成了使用@..@占位符(你可以使用Maven属性resource.delimiter来覆盖)。

2. 使用Spring Boot Maven插件

Spring Boot包含了一个Maven插件,这个插件可以将工程打包为一个可执行的jar包。如果你向使用它的话,将它添加到你的plugins部分:

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

如果你想使用Spring Boot的starter parent pom,你只需要添加这个插件,不需要配置它,除非你想更改父POM中的定义的设置。

3. Starters

通过Starters你可以获得相关技术的一站式服务所有官方的启动器都有一个类似的命名模式:spring-boot-starter-*,*是应用特性类型, 下面的应用启动器由Spring Boot提供,在org.springframework.boot组下:

Spring Boot 应用启动器

Name Description
spring-boot-starter-thymeleaf Starter for building MVC web applications using Thymeleaf views
spring-boot-starter-data-couchbase Starter for using Couchbase document-oriented database and Spring Data Couchbase
spring-boot-starter-artemis Starter for JMS messaging using Apache Artemis
spring-boot-starter-web-services Starter for using Spring Web Services
spring-boot-starter-mail Starter for using Java Mail and Spring Framework’s email sending support
spring-boot-starter-data-redis Starter for using Redis key-value data store with Spring Data Redis and the Jedis client
spring-boot-starter-web Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
spring-boot-starter-data-gemfire Starter for using GemFire distributed data store and Spring Data GemFire
spring-boot-starter-activemq Starter for JMS messaging using Apache ActiveMQ
spring-boot-starter-data-elasticsearch Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch
spring-boot-starter-integration Starter for using Spring Integration
spring-boot-starter-test Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito
spring-boot-starter-jdbc Starter for using JDBC with the Tomcat JDBC connection pool
spring-boot-starter-mobile Starter for building web applications using Spring Mobile
spring-boot-starter-validation Starter for using Java Bean Validation with Hibernate Validator
spring-boot-starter-hateoas Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS
spring-boot-starter-jersey Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web
spring-boot-starter-data-neo4j Starter for using Neo4j graph database and Spring Data Neo4j
spring-boot-starter-websocket Starter for building WebSocket applications using Spring Framework’s WebSocket support
spring-boot-starter-aop Starter for aspect-oriented programming with Spring AOP and AspectJ
spring-boot-starter-amqp Starter for using Spring AMQP and Rabbit MQ
spring-boot-starter-data-cassandra Starter for using Cassandra distributed database and Spring Data Cassandra
spring-boot-starter-social-facebook Starter for using Spring Social Facebook
spring-boot-starter-jta-atomikos Starter for JTA transactions using Atomikos
spring-boot-starter-security Starter for using Spring Security
spring-boot-starter-mustache Starter for building MVC web applications using Mustache views
spring-boot-starter-data-jpa Starter for using Spring Data JPA with Hibernate
spring-boot-starter Core starter, including auto-configuration support, logging and YAML
spring-boot-starter-groovy-templates Starter for building MVC web applications using Groovy Templates views
spring-boot-starter-freemarker Starter for building MVC web applications using FreeMarker views
spring-boot-starter-batch Starter for using Spring Batch
spring-boot-starter-social-linkedin Stater for using Spring Social LinkedIn
spring-boot-starter-cache Starter for using Spring Framework’s caching support
spring-boot-starter-data-solr Starter for using the Apache Solr search platform with Spring Data Solr
spring-boot-starter-data-mongodb Starter for using MongoDB document-oriented database and Spring Data MongoDB
spring-boot-starter-jooq Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc
spring-boot-starter-jta-narayana Spring Boot Narayana JTA Starter
spring-boot-starter-cloud-connectors Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku
spring-boot-starter-jta-bitronix Starter for JTA transactions using Bitronix
spring-boot-starter-social-twitter Starter for using Spring Social Twitter
spring-boot-starter-data-rest Starter for exposing Spring Data repositories over REST using Spring Data REST

除了应用启动器之外,下面的启动器可以用来添加产品准备功能:

Spring Boot 产品启动器

Name Description
spring-boot-starter-actuator Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application

最后,如果你想排除或交换特定的技术方面,Spring Boot也包括一些可以使用的启动器:

Spring Boot 技术启动器

Name Description
spring-boot-starter-undertow Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat
spring-boot-starter-jetty Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat
spring-boot-starter-logging Starter for logging using Logback. Default logging starter
spring-boot-starter-tomcat Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web
spring-boot-starter-log4j2 Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging
4. 使用“default”包

当一个类没有包含一个package声明时,它当做是在default package中。通常情况下不建议使用default package,应该避免使用它。当Spring Boot应用使用@ComponentScan@EntityScan@SpringBootApplication它会引起一些特别的问题,因为Spring Boot会读取每个jar中的每个类。

Java推荐的包命名规范,使用一个反转的域名(例如,com.example.project)。

5. 主应用类的定义

通常主应用类是放在其他类之上的根包中,这里展示一个典型的布局:

com+- example+- myproject+- Application.java|+- domain|   +- Customer.java|   +- CustomerRepository.java|+- service|   +- CustomerService.java|+- web+- CustomerController.java

其中Application.java即是主类,@EnableAutoConfiguration注解经常放在你的主类(main class)中,对于某些像它隐式的定义了一个基search package,例如,如果你正在写一个JPA应用,@EnableAutoConfiguration注解的类所在的包将被用来搜索@Entity项。根包的应用也允许使用@ComponentScan注解而不需要指定basePackage特性。如果你的主类是在根包中,你也可以使用@SpringBootApplication注解。

Application.java文件会声明main方法和基本的@Configuration

package com.example.myproject;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

可以直接使用SpringBootApplication代替这三个注解(其实是两个,@ComponentScan会自动获取所有Spring组件,包括@Configuration

同时,不必将所有的@Configuration放入一个单独的类,可以通过@Import导入额外的配置类,当然正如上文所说, @ComponentScan来自动获得

如果绝对的必须使用基于XML的配置,推荐仍然从@Configuration类开始,使用额外的@ImportResource注解来加载XML配置文件。

@EnableAutoConfiguration@SpringBootApplication注解 会自动的将已经添加在Spring的依赖配置成bean, 如果你发现正在应用特定的你不想使用的自动配置类,你可以使用@EnableAutoConfiguration注解的exclude特性来禁用它们。 如:

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
6. 开发工具

pring Boot包含额外的工具集合,可以使应用开发的过程更方便一点。spring-boot-devtools模块可以包含进任何工程,用来提供额外的程序调试特性。为了添加工具支持,简单的添加模块依赖到你的构建系统中:

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>
</dependencies>

自动重启

classpath中的文件修改时,使用spring-boot-devtools的应用会自动重启。当使用IDE开发时,这是一个很有用的功能,因为代码改变时它能快速的进行反馈。默认情况下,会监控classpath指向的文件夹中任何条目的变化。注意某些资源例如静态资源和视图模板不需要重启应用。

DevTools依赖应用上下文关闭钩子来进行重启期间的关闭。如果你禁用了关闭钩子它将不能正确工作(SpringApplication.setRegisterShutdownHook(false))。

当决定classpath中输入引起的改变是否应该触发重启时,DevTools会自动忽略命名为spring-bootspring-boot-devtoolsspring-boot-autoconfigurespring-boot-actuatorspring-boot-starter的工程。

某些资源当它们改变时不一定需要触发重启。默认情况下,/META-INF/maven/META-INF/resources/resources/static/public/templates中资源的改变不会触发重启,但会触发实时重载。如果你想定制这些例外项,你可以使用spring.devtools.restart.exclude属性。例如,仅排除/static/public,设置如下:

spring.devtools.restart.exclude=static/**,public/**

如果你想使用重启功能你可以通过spring.devtools.restart.enabled属性禁用它。

public static void main(String[] args) {System.setProperty("spring.devtools.restart.enabled", "false");SpringApplication.run(MyApp.class, args);
}

实时重载

spring-boot-devtools模块包含一个内嵌的实时重载服务器,当资源改变时可以用来触发浏览器重新刷新。 当你的应用运行时,如果你不想启动实时重载服务器,你可以将spring.devtools.livereload.enabled属性设为false

一次你只可以运行一个实时重载服务器。在启动你的应用之前,确保没有其它的实时重载服务器在运行。如果你从你的IDE中启动多个应用,只有第一个应用有实时重载服务器支持。

二、Spring Boot 特性

1. 应用事件和监听器

除了平常的Spring框架事件之外,例如ContextRefreshedEventSpringApplication会发送一些其它的应用事件。

ApplicationContext创建之前实际上会触发一些事件,因此你不能使用@Bean来注册这些监听器。你可以通过SpringApplication.addListeners(…)SpringApplicationBuilder.listeners(…)方法来注册这些监听器。

如果你想自动注册这些监听器,不管上下文的创建方式,你可以在你的工程中添加META-INF/spring.factories文件,并通过org.springframework.context.ApplicationListener作为key来引用你的监听器。

org.springframework.context.ApplicationListener=com.example.project.MyListener

当你的应用运行时,应用事件以下面的顺序发送:

  1. 在运行启动时发送ApplicationStartedEvent,除了监听器和初始化器注册之外,在进行任何处理之前发送。
  2. 当在上下文中使用的Environment已知时,发送ApplicationEnvironmentPreparedEvent,但发送是在上下文创建之前。
  3. 在再刷新启动之前,但在bean定义加载之后,发送ApplicationPreparedEvent
  4. 在再刷新之后,发送ApplicationReadyEvent,任何相关的回调函数都处理完成之后,意味着应用已经准备处理服务请求了。
  5. 如果启动时出现异常,发送ApplicationFailedEvent.
2. Web环境

SpringApplication会尝试创建代表你的合适的ApplicationContext类型。默认情况下,会使用AnnotationConfigApplicationContextAnnotationConfigEmbeddedWebApplicationContext,依赖于你是否在开发一个web应用。

使用的决定web environment的算法是相对简单的(基于现有的一些类)。如果你需要覆写默认值你可以使用setWebEnvironment(boolean webEnvironment)

当在JUnit测试时使用SpringApplication,经常需要调用setWebEnvironment(false)

3. 使用ApplicationRunner或CommandLineRunner

如果你需要在SpringApplication启动时运行一些特定的代码,你可以实现ApplicationRunnerCommandLineRunner接口。这两个接口以同样方式工作,并有一个单独的run方法,在SpringApplication.run(…)之前会调用这个run方法。

CommandLineRunner接口提供了对应用参数的访问,应用参数作为一个简单的字符串数组,而ApplicationRunner使用前面描述的ApplicationArguments接口。

import org.springframework.boot.*
import org.springframework.stereotype.*@Component
public class MyBean implements CommandLineRunner {public void run(String... args) {// Do something...}}

另外,如果定义的CommandLineRunnerApplicationRunner beans必须以指定顺序调用,你可以实现org.springframework.core.Ordered接口或org.springframework.core.annotation.Order 注解。

4. 应用退出

为了确保ApplicationContext在关闭时安全退出, 每个SpringApplication都会在JVM中注册一个关闭钩子。所有的标准Spring生命周期回调函数(例如DisposableBean接口,或@PreDestroy注解)都会被使用。

另外,当应用退出时,如果它们想返回一个特定的退出码,beans可以实现org.springframework.boot.ExitCodeGenerator接口。

5. 外部配置

Spring Boot允许你进行外部化配置,因此可以将同样的应用代码在不同的环境中运行。你可以使用属性文件,YAML文件,环境变量和命令行参数来进行外部化配置。

5.1 配置随机值

当注入随机值时,RandomValuePropertySource是很有用的(例如,注入秘密或测试用例)。它可以产生integerslongsuuidsstrings,例如:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
5.2 应用属性文件

SpringApplication会从以下位置的application.properties文件中加载属性并将它们添加到Spring的Environment中:

  1. 当前目录的子目录/config
  2. 当前目录
  3. classpath中的/config
  4. classpath的根目录

这个列表是按优先级排序的(在更高位置的属性会重写定义在更低位置的属性)。

你也可以使用YAML(.yml)文件来代替.properties文件。

5.3 属性中的占位符

当使用application.properties中的值时,会通过现有的Environment进行过滤,因此你可以参考前面定义的值(例如从系统属性中)。

app.name=MyApp
app.description=${app.name} is a Spring Boot application
5.4 使用YAML代替Properties

YAML是JSON的超集,它可以用一种非常方便的形式来指定分层配置数据。当你的类路径有SnakeYAML库时,SpringApplication类自动支持YAML作为properties的一个替代品。

如果你使用‘Starters’,SnakeYAML将由spring-boot-starter自动提供。

加载YAML

Spring框架提供了两个类用来方便的加载YAML文档。YamlPropertiesFactoryBean将加载YAML作为PropertiesYamlMapFactoryBean将加载YAML作为Map

例如,下面的YAML文档:

environments:dev:url: http://dev.bar.comname: Developer Setupprod:url: http://foo.bar.comname: My Cool App

将被转换成这些属性:

environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App

YAML列表通过[index]解引用表示为属性的key,例如这个YAML:

my:servers:- dev.bar.com- foo.bar.com

将被转换成这些属性:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

为了像使用Spring的DataBinder一样(@ConfigurationProperties的功能)绑定这些属性,你需要在类型为java.util.List(或Set)的目标bean中有属性,你需要提供一个setter或用一个可变的值来对它初始化,例如,绑定上面的属性值:

@ConfigurationProperties(prefix="my")
public class Config {private List<String> servers = new ArrayList<String>();public List<String> getServers() {return this.servers;}
}
6. Profiles

Spring Profiles提供了一种隔离部分应用配置的方式,并让这些配置只在特定的环境生效。任何带有@Profile标记的@Component@Configuration在加载时都会受限制:

@Configuration
@Profile("production")
public class ProductionConfiguration {// ...}

以正常的Spring方式,你可以使用spring.profiles.active Environment属性来指定激活哪一个profiles。你可以在任何常见的方式指定这个属性,例如你可以在你的application.properties中包含它:

spring.profiles.active=dev,hsqldb

或在命令行用--spring.profiles.active=dev,hsqldb指定。

7. Logging

默认情况下,如果使用Starters,Logback将作为日志。也要包含恰当的Logback规则来保证依赖库使用Java Util Logging,Commons Logging,Log4J或SLF4J都能正确工作。

在Java中有许多日志框架可用。不必担心上面的列表看起来有点混乱。通常情况下你不需要改变你的日志依赖,Spring Boot默认情况下能很好的工作。

日志级别

Spring支持的所有日志系统都可以在Spring的Environment中设置日志级别(例如在application.properties设置),使用logging.level.*=LEVEL进行设置,LEVEL是TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF中的一个。root日志器可以用logging.level.root来配置。例如在application.properties中:

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

默认情况下Spring Boot重新映射Thymeleaf的INFO信息,为了它们能在DEBUG级别进行输出。这能帮助减少标准日志输出中的噪声。关于怎样在你自己的配置中使用重新映射的更多细节请看LevelRemappingAppender

Spring Boot 官方文档摘要相关推荐

  1. Spring Boot 官方文档学习(一)入门及使用

    Spring Boot 官方文档学习(一)入门及使用 个人说明:本文内容都是从为知笔记上复制过来的,样式难免走样,以后再修改吧.另外,本文可以看作官方文档的选择性的翻译(大部分),以及个人使用经验及问 ...

  2. 【Spring Boot官方文档原文理解翻译-持续更新中】

    [Spring Boot官方文档原文理解翻译-持续更新中] 文章目录 [Spring Boot官方文档原文理解翻译-持续更新中] Chapter 4. Getting Started 4.1. Int ...

  3. Spring Boot 官方文档中文版

    目前为最新版 2.5.5. 其他spring文档不断更新中 目前为最新版 2.5.5. 其他spring文档不断更新中 总目录 Spring Boot Reference Documentation ...

  4. 《Spring Boot官方文档》16. 自动配置

    16. 自动配置 Spring Boot的自动配置会尝试根据你添加进来的jar依赖来自动配置你的Spring应用.例如,如果HSQLDB在你的classpath路径上,你没有手动配置任何数据库连接实体 ...

  5. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(二)

    接前一篇 Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 本篇主要内容:Spring Type Conver ...

  6. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion

    本篇太乱,请移步: Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 写了删删了写,反复几次,对自己的描述很不 ...

  7. 如何找到spring的官方文档位置

    最近因为项目中遇到了一些问题, 百度不到比较好的方案, 就准备去看下spring的官方文档,  在此记录下: 1. 进入spring framework的官网项目页面: https://spring. ...

  8. 如何找到spring的官方文档

    最近因为项目中遇到了一些问题, 百度不到比较好的方案, 就准备去看下spring的官方文档,  在此记录下: 1. 进入spring framework的官网项目页面: https://spring. ...

  9. Spring指南之使用Spring缓存数据(Spring Framework官方文档之缓存抽象详解)

    1.请参见官方文档Spring指南之使用 Spring 缓存数据 2.请参见Spring官方文档之缓存抽象 3.参见github代码 文章目录 一.简介 二.你将创造什么(What You Will ...

最新文章

  1. Linux文件/目录 所有者/所在组
  2. java线程安全问题之静态变量、实例变量、局部变量
  3. (3)zynq FPGA AXI4_Stream总线介绍
  4. XOS 详解1: os_s_xxxx.s
  5. c语言学习-从键盘上输入100个字符,统计其中字母、每个数字和其它字符的个数及其百分比
  6. HDU-1233-还是畅通工程(最小生成树)
  7. 6美元进公园随便挖钻石
  8. Tomcat启动提示At least one JAR was scanned for TLDs yet contained no TLDs
  9. 159.majority element
  10. 分布式常见面试题总结(2021)
  11. USPS手写体数据的处理
  12. MFC TabCtrl 控件修改标签尺寸
  13. 解决报错:org/springframework/util/backoff/BackOff
  14. InfluxDB添加用户认证
  15. python 抓取网页数据
  16. 从单机到2000万 QPS 并发的 Redis 高性能缓存实践之路
  17. unsupported format character Y (0x59) at index 167
  18. (附源码)springboot高校学生健康打卡系统的设计与实现 毕业设计 021009
  19. self.font = core.getfont(font, size, index, encoding, layout_engine=layout_engine) OSError: cannot o
  20. MySql删除列(多列)

热门文章

  1. 3704对象关闭时_对象关闭时,不允许操作,运行时错误3704
  2. MFC CString的GetBuffer()/ReleaseBuffer()
  3. 手工测试用例与自动化测试用例的区别
  4. Linux ❀ RHCE自研教学笔记 - Redhat 8.2 Nmcli服务教研笔记
  5. 移动端 Iphone拍照变横问题的解决
  6. TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('S32')
  7. deeplabv3+ 论文相关参数 代码解析 Flip MS SC random crop
  8. jupyter notebook桌面图标变白,解决方法
  9. python GUI 绑定事件
  10. Java中脚手架是干什么用的_如何理解面向对象?