原文地址:
https://docs.spring.io/spring-boot/docs/2.3.3.RELEASE/reference/htmlsingle/#boot-documentation
随缘翻译法:看我眼色翻译。夹带私货。有些直接就没有翻译,而是将自己的理解写上去了
提示:第2,3章节是基础内容。一般0基础建议先看这个。但是因为我不是0基础,基本上浏览一遍就过去了
第四章节才是我看官方文档的目的
2. 开始
如果你打算开始SpringBoot,或者Spring,从阅读这部分开始。这里会回答基础的问题:例如:SpringBoot是什么?怎么用,为什么用SpringBoot?这部分还包括结束Springboot以及安装说明书。我们将带你构建你的第一个SpringBoot应用。已经将我们所知道的核心原则都告诉你。
2.1 SpringBoot介绍
SpringBoot帮助你创建一个独立地,生产级别的,基于Spring的一个你可以运行的应用。我们在Spring平台和第三方lib采取一些约定俗成的配置。使你可以以最小的代价开始SpringBoot应用。大多数情况下,只需要很少的Spring配置。
你可以使用Springboot创建一个使用java -jar
命令运行的jar包,也可以创建更传统的war包。 我们也提供可以运行“spring scripts”的命令行工具
我们主要目标是:
- 为所有的Spring开发提供一个非常快速且易于使用的入门体验。
- 开箱即用,但是当需求和默认值有偏离的时候,将控制权交给你(ps:我们提供默认配置可以使用,但是如果你想修改配置,以使用者的为准,使用者可以完全控制所有配置)
- 提供一系列大型项目通用的非功能特性(例如内嵌服务器,security, metrics, health checks, and externalized configuration)
- 绝对没有任何代码生成和必须的XML配置
2.2 环境要求
SpringBoot 2.3.3 发行版要求至少JDK8,也支持之上的版本,直到JDK14 . Spring Framework 5.2.8.发行版或更新的版本也是这个要求
以下构建工具是明确支持的:
构建工具 | 版本 |
---|---|
Maven | 3.3+ |
Gradle | 6.3+ (5.6.x也支持,但是不推荐使用) |
2.2.1 Servlet 容器
SpringBoot支持下面这些内嵌的Servlet容器
名字 | Servlet版本 |
---|---|
Tomcat 9.0 | 4.0 |
Jetty 9.4 | 3.1 |
Undertow 2.0 | 4.0 |
你也可以部署SpringBoot应用到任何其他支持Servlet3.1的容器
2.3 安装SpringBoot
SpringBoot可以通过”经典的“Java开发工具(ps:IDEA)使用,也可以通过命令行工具安装使用。不管用上面那种方式,你需要确保的JDK版本是1.8或者更高的版本。开始之前,先使用下面的命令赖检查你的安装的JDK版本吧:
java -version
除非你是刚开始转到Java开发或你想体验下SpringBoot,你可能先想尝试用SpringBootCLI。否则,请直接阅读“经典”安装说明(PS:这里是推荐用IDEA或者eclipse的Java开发工具开始进行SpringBoot应用开发)。
2.3.1 写给Java开发者的安装说明
你可以和使用标准Java lib一样方式使用SpringBoot。 相同的,需要导入spring-boot-*.jar
jar包到你的classpath下。SpringBoot不要求任何特别的集成工具,所有你可以使用任何IDE或者直接使用文本编辑器。同样的,SpringBoot应用也没有什么特殊的地方,你可以像debug其他任何java 程序一样debug SpringBoot应用。
尽管你可以直接通过下载SpringBoot的相关jar包收到导入进行开发。但是我们还是建议你使用构建工具。(例如Maven或者Gradle)
maven方式安装SpringBoot
SpringBoot支持Maven3.3以上的版本。如果你还没有安装好Maven,你可以跟着这里的 maven.apache.org.文档操作
这里写的是操作系统可以通过什么方式获得maven,我就不翻译了
SpringBoot依赖使用 org.springframework.book
groupId . 典型的,你的Maven POM文件继承自spring-boot-starter-parent
项目。而且声明了一个或多个“Starters” (ps:这里的starter指的是类似spring-boot-starter-web这种声明) SpringBoot也提供了一种可选的maven插件来创建一个可执行的jar
这里是我的备注
上面的说的可选的插件是这个:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>
更多的通过Maven开始一个SpringBoot应用细节可以在这里:Getting Started section 找到
Gradle方式开始SpringBoot
SpringBoot兼容Gradle6.3 以上的版本,虽然你可以使用Gradle5.6.x,但是我们不推荐。因为我们之后的版本不对5.6.x最兼容适配了。如果你没有安装Gradle,你可以看这里:gradle.org.
SpringBoot依赖使用 org.springframework.book
groupId . 典型的,你的项目声明了一个或多个“Starters” (ps:这里的starter指的是类似spring-boot-starter-web这种声明) SpringBoot也提供了一种可选的gradle插件来创建一个可执行的jar (PS:这里和上面maven说的是一样的。但是这里我平时不用gradle,所以我不知道那个插件指的什么)
这里夸了一下Gradle, 意思是用Gradle,声明语句比较简洁。我就不翻译了
更多的通过Gradle 开始SpringBoot开发细节这里:Getting Started section
2.3.2 安装Spring Boot CLI
在上面的 2.3 安装SpringBoot 里面就说了。除非你是新入门的Java开发。或者你是想体验下SpringBootCLI,否则不建议你用这个。既然作者都不建议。我就不翻译了。不浪费时间
2.3.3 从早期的SpringBoot升级
说了些客套话,文章建议如果你想从早期的SpringBoot升级。请参考下面两个文档
“migration guide” on the project wiki
需要注意到的是添加新的配置以及移除旧的配置
2.4 开发你的第一个SpringBoot的应用
这个章节将指导你如何开发一个 “Hello world” 的web应用程序。并会特别之处SpringBoot的关键特征。我们使用maven构架项目,因为大多是IDE都支持。
又说了些废话,大意思你可以中下面的网站获得帮助:
spring.io (PS:则指向官网首页,这个难道不是废话。我TM现在就在官网,然后你让我官网绕一圈再回来?)
在开始前,请打开你的终端或命令行窗口 (linux的terminal 或windows的 CMD)运行一下命令来确认你安装了合适JDK和maven
$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
$ mvn -v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
注意:这个简单的操作需要你提前配置好环境变量。
2.4.1 创建POM
我们需要从pmo.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 https://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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
</parent>
<description/>
<developers>
<developer/>
</developers>
<licenses>
<license/>
</licenses>
<scm>
<url/>
</scm>
<url/>
<!-- Additional lines to be added here... -->
</project>
下面的内容就是如何用SpringBoot写一个helloworld的web程序。随便找个博客都能看到。我就不翻译了
一些关键的信息我挑出来
- 导包
- 编辑controller文件
- 写启动类
如何想打jar包,还得引入maven的一个插件
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
jar包会生成在项目的target目录下
运行
java -jar jar包的名字.jar
3. 使用Springboot(这里才算是正文开始)
3.1 构建系统
前4个小结讲的是1.依赖管理(就是关了jar包)相关的信息,2. maven 工具,3Gradle工具,Ant工具
备注(现在最多人用的是Maven。但是被吹的最好的是gradle。但是我还是选择的maven。用的人多,那么出现问题更容易找到解决方案)
3.1.5 起步依赖
这里解释了下起步依赖是什么。但是我懒得翻译了。我直接告诉你:就是起步依赖是一系列依赖的合计,例如你导入了
spring-boot-starter-web
会帮你将mvc,Spring ,log相关你可能需要的依赖都导入进去。而且这些依赖之间的兼容性是经过过Spring的人测试过的。这些依赖不会有版本之前的冲突,你可以放心使用。
表一: Springboot相关起步依赖
这些东西如果给翻译了。反而不容易理解了。不翻译
名字 | 描述 |
---|---|
spring-boot-starter | Core starter, including auto-configuration support, logging and YAML |
spring-boot-starter-activemq | Starter for JMS messaging using Apache ActiveMQ |
spring-boot-starter-amqp | Starter for using Spring AMQP and Rabbit MQ |
spring-boot-starter-aop | Starter for aspect-oriented programming with Spring AOP and AspectJ |
spring-boot-starter-artemis | Starter for JMS messaging using Apache Artemis |
spring-boot-starter-batch | Starter for using Spring Batch |
spring-boot-starter-cache | Starter for using Spring Framework’s caching support |
spring-boot-starter-data-cassandra | Starter for using Cassandra distributed database and Spring Data Cassandra |
spring-boot-starter-data-cassandra-reactive | Starter for using Cassandra distributed database and Spring Data Cassandra Reactive |
spring-boot-starter-data-couchbase | Starter for using Couchbase document-oriented database and Spring Data Couchbase |
spring-boot-starter-data-couchbase-reactive | Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive |
spring-boot-starter-data-elasticsearch | Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch |
spring-boot-starter-data-jdbc | Starter for using Spring Data JDBC |
spring-boot-starter-data-jpa | Starter for using Spring Data JPA with Hibernate |
spring-boot-starter-data-ldap | Starter for using Spring Data LDAP |
spring-boot-starter-data-mongodb | Starter for using MongoDB document-oriented database and Spring Data MongoDB |
spring-boot-starter-data-mongodb-reactive | Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive |
spring-boot-starter-data-neo4j | Starter for using Neo4j graph database and Spring Data Neo4j |
spring-boot-starter-data-r2dbc | Starter for using Spring Data R2DBC |
spring-boot-starter-data-redis | Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client |
spring-boot-starter-data-redis-reactive | Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client |
spring-boot-starter-data-rest | Starter for exposing Spring Data repositories over REST using Spring Data REST |
spring-boot-starter-data-solr | Starter for using the Apache Solr search platform with Spring Data Solr |
spring-boot-starter-freemarker | Starter for building MVC web applications using FreeMarker views |
spring-boot-starter-groovy-templates | Starter for building MVC web applications using Groovy Templates views |
spring-boot-starter-hateoas | Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS |
spring-boot-starter-integration | Starter for using Spring Integration |
spring-boot-starter-jdbc | Starter for using JDBC with the HikariCP connection pool |
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-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-json | Starter for reading and writing json |
spring-boot-starter-jta-atomikos | Starter for JTA transactions using Atomikos |
spring-boot-starter-jta-bitronix | Starter for JTA transactions using Bitronix. Deprecated since 2.3.0 |
spring-boot-starter-mail | Starter for using Java Mail and Spring Framework’s email sending support |
spring-boot-starter-mustache | Starter for building web applications using Mustache views |
spring-boot-starter-oauth2-client | Starter for using Spring Security’s OAuth2/OpenID Connect client features |
spring-boot-starter-oauth2-resource-server | Starter for using Spring Security’s OAuth2 resource server features |
spring-boot-starter-quartz | Starter for using the Quartz scheduler |
spring-boot-starter-rsocket | Starter for building RSocket clients and servers |
spring-boot-starter-security | Starter for using Spring Security |
spring-boot-starter-test | Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito |
spring-boot-starter-thymeleaf | Starter for building MVC web applications using Thymeleaf views |
spring-boot-starter-validation | Starter for using Java Bean Validation with Hibernate Validator |
spring-boot-starter-web | Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container |
spring-boot-starter-web-services | Starter for using Spring Web Services |
spring-boot-starter-webflux | Starter for building WebFlux applications using Spring Framework’s Reactive Web support |
spring-boot-starter-websocket | Starter for building WebSocket applications using Spring Framework’s WebSocket support |
表二
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 |
表三
Name | Description |
---|---|
spring-boot-starter-jetty | Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat |
spring-boot-starter-log4j2 | Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging |
spring-boot-starter-logging | Starter for logging using Logback. Default logging starter |
spring-boot-starter-reactor-netty | Starter for using Reactor Netty as the embedded reactive HTTP server. |
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-undertow | Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat |
3.2 代码结构推荐
3.3 配置类
3.4 自动配置
3.5 SpringBean 和依赖注入
你可以随便使用任何Spring框架标准技术来定义你们的bean以及他们的依赖注入。我们通常使用@ComponentScan
(申明将这个bean交给Spring管理)和@Autowired
(构造函数注入)配合的方式
如果你向2.3章节那样用标准的方式组织你的代码的话。可以添加@ComponentScan
注解,且不需要任何参数(在你的启动类上),可以使你的所有组件(@Component, @Service, @Repository, @Controller 等注解声明的bean)都会注册到SpringBean里面
下面是Service的一个示范代码
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
你可以也省略**@Autowire** 注解。
注意我们是将RiskAssessor 声明为final类型是为了避免随后这个应用类型被改变。
这是我的注释: 这种Service默认是单例的。声明周期从程序开始一直到程序结束。而且也没有其他的成员变量。声明为final可以避免被改变。而且可以让我们确信是线程安全的
3.6 使用 @SpringBootApplication注解
我直接告诉你这部分内容的意思: @SpringBootApplication 注解相当于 @EnableAutoConfiguration, @ComponentScan, @Configuration 三个注解的合集
开启自动配置,组件扫描,声明这是个配置文件
package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.7 运行程序
3.8 部署工具
3.9 打包程序到生产环境
3.10 后序推荐阅读
4. SpringBoot的详细特征
如果你对SpringBoot没有一点基础,请先阅读第2章节和第3章节
4.1 SpringApplication
SpringApplication类提供了一种方便的方法来引导从main()方法启动的Spring应用程序
不知道有没人注意过。这个就是我们SpringBoot的的启动类使用的方法
如果程序没有错误,运行下面的程序就能启动我们的Springboot程序
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.1.1 启动失败(Startup Failure)
如果你启动SpringBoot应用失败,Springboot会在控制台打印出可能的失败原因以及给出解决失败的建议
4.1.2 延迟初始化(Lazy Initialization)
(也有叫懒加载的)如果开启了延迟初始化,bean只要到其被使用的时候才被初始化,而不是应用启动的时候。懒加载可以减少应用的启动时间。
延迟加载也有缺点:问题不能及早暴露出来,有些bean可能无法被初始化,但是启动应用的时候不知道。而且有可能内存不足,但是因为延迟加载,启动时候内存是够的,但是后面加载发现内存不够用了。所以默认情况下是关闭延迟加载的。这里给的建议是:第一次不启用延迟加载运行。如果后序有需要再开启延迟加载
延迟加载可以使用配置文件配置
spring.main.lazy-initialization=true
或者使用注解@Lazy(false)
4.1.3 Customizing the Banner(自定义横幅)
4.1.4 自定义Spring应用
4.1.5 流式构建API
4.1.6 程序可用性
4.1.7 应用事件和监听
4.1.8 web环境
4.1.9 Accessing Application Arguments
4.2 外部配置
Springboot应用可以读取外部配置文件,例如.yml
文件 .properties
。还可以读取计算机的环境变量,以及可以接受命令行参数里输入的参数
4.2.1 配置随机值(我之前还不知道有这个功能)
可以配置如下多种类型的随机值。可以用来做验证码。不用直接写程序生成
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]}
4.2.2 可以命令行参数
例如下面这种 通过--
分隔
java -jar news-0.0.1-SNAPSHOT.jar --spring.profiles.active=test --server.port=8082
4.2.3 加载属性文件
springboot应用会自动加载.yml
文件和 .properties
如果他们放在下面目的下:
- 当前目录的/config目录下
- 当前目录下
- classpath目录的/config下
- classpath
也可以运行的时候指定加载那个地方的配置文件
java -jar myproject.jar --spring.config.name=myproject
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
4.2.4 不同环境加载不同的属性配置文件
配置文件命名为application-{profile}.properties
(.yml同样)
就可以在启动应用的时候通过--spring.profiles.active={profile}
指定使用哪个配置文件了
如果没有在运行时指定:默认使用application-default.properties
如果你的配置文件目录下就一个配置文件。那就自动加载那个了
也可用通过spring.config.location
指定。例如java -jar myproject.jar --spring.config.name=myproject
或spring.config.location=classpath:/default.properties,classpath:/override.properties
4.2.5 属性文件中的占位符
app.name=MyApp
app.description=${app.name} is a Spring Boot application
4.2.6 属性加密
Springboot是不支持加密属性的。但是一共了必要的hook points。想了解详细信息需要点击 Customize the Environment or ApplicationContext Before It Starts
4.2.7 使用yml取代properties文件
看下面的示例,yaml文件要简洁很多。但是yaml无法支持@PropertySource
注解
environments:
dev:
url: https://dev.example.com
name: Developer Setup
prod:
url: https://another.example.com
name: My Cool App
environments.dev.url=https://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=https://another.example.com
environments.prod.name=My Cool App
4.2.8 类型安全的配置文件
这一节讲各种配置文件。
但是我们常用的其实就是用.yml
或.properties
然后通过@PropertySource
或@ConfigurationProperties
读取
不想详细看那么多
4.3 profiles
就是讲了不用的环境可以设置不同的配置文件
就是利用 spring.profiles.active={profiles}
4.4 日志
springboot使用Commons日志记录所有内部日志,同时Java Util log、Log4J2和Logback提供了默认配置。日志都被预先配置为使用控制台输出,当然你可以配置为文件输出。
logback是默认的日志工具。但是也包含了Util Logging, Commons Logging, Log4J, or SLF4J 的依赖。你可以自己设置
4.4.1 日志格式
2019-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52
2019-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms
2019-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
日志输出包含:
- 时间
- 日志级别:ERROR, WARN, INFO, DEBUG, TRACE (按顺序排列级别。高—>低)
- 线程id
---
分割线- 线程名字
- logger名字。一般我们使用发生错误的类名
- 日志具体醒醒
备注:logback没有FATAL这个日志级别
4.4.2 控制台输出日志
默认日志输出级别是INFO,你也可以在配置文件改成debug
在控制台输出日志是可以配置颜色的。但是我觉得没必要搞得这么华丽呼哨,使用默认的就好了。
4.4.3 文件输出日志
属性文件里面配置即可 logging.file.name
orlogging.file.path
4.4.4 日志级别
4.4.5 日志组
4.4.6 个性化日志配置
4.5 国际化
我以前一直不知道国际化是什么?原来所谓的国际化就是换语言。
详情点击MessageSourceProperties
我个人觉得这种国际化肯定不好用。毕竟是机器翻译。没有什么太大的实用性。如果想做国际化,还是得靠人来翻译
4.6 JSON
SpringBoot 起步依赖包含了下面三种Json包
- Jackson (默认的)
- Gson
- JSON-B
默认的就挺好使用了。如果想用其他额,推荐使用Fastjson