提交 1c91b2de 编写于 作者: 茶陵後's avatar 茶陵後 👍

#1 添加英文原文(1)

上级 2c5f25dc
此差异已折叠。
# Spring 中文文档社区
从实操的角度整理翻译`Spring`相关文档,包括`快速开始``安装指南``开发工具配置``代码案例`等。
## 声明
本站中的文章内容来源于 [Spring.io](https://spring.io/),原始版权归属于 [Spring.io](https://spring.io/)。本站对相关文章进行了翻译及整理。本站文章可供个人学习、研究或者欣赏之用,未经本站事先书面许可,不得进行任何转载、商用或与之相关的行为。
商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。
## 文档列表
- [Spring](/en/spring/why-spring.html)
- [Spring Boot](/en/spring-boot/getting-help.html)
- [Spring Framework](/en/spring-framework/overview.html)
- [Spring Data](/en/spring-data/spring-data.html)
- [Spring Cloud](/en/spring-cloud/documentation-overview.html)
- [Spring Cloud Data Flow](/en/spring-cloud-data-flow/spring-cloud-dataflow.html)
- [Spring Security](/en/spring-security/overview.html)
- [Spring for GraphQL](/en/spring-for-graphql/spring-graphql.html)
- [Spring Session](/en/spring-session/_index.html)
- [Spring Integration](/en/spring-integration/preface.html)
- [Spring HATEOAS](/en/spring-hateoas/spring-hateoas.html)
- [Spring REST Docs](/en/spring-rest-docs/spring-restdocs.html)
- [Spring Batch](/en/spring-batch/spring-batch-intro.html)
- [Spring AMQP](/en/spring-amqp/spring-amqp.html)
- [Spring CredHub](/en/spring-credhub/spring-credhub.html)
- [Spring Flo](/en/spring-flo/spring-flo.html)
- [Spring for Apache Kafka](/en/spring-for-apache-kafka/spring-kafka.html)
- [Spring LDAP](/en/spring-ldap/spring-ldap.html)
- [Spring Shell](/en/spring-shell/spring-shell.html)
- [Spring Statemachine](/en/spring-statemachine/spring-statemachine.html)
- [Spring Vault](/en/spring-vault/spring-vault.html)
- [Spring Web Flow](/en/spring-web-flow/preface.html)
- [Spring Web Services](/en/spring-web-services/spring-web-service.html)
## 参与贡献流程
所有 **`Java Spring 熟练使用者`** 可以参与到`Spring 中文文档社区`的建设中来,选择自己感兴趣题目,可以直接撰写文章,也可以翻译 [Spring 官方](https://spring.io/) 上面的内容,也可以校对别人翻译的文章。具体贡献流程如下。
![](./readme/readme-1.png)
### 1. 阅读文档帮助改善
[`Spring 中文文档社区`](https://spring.gitcode.net)上浏览某一篇文档时,发现有不准确的地方,可以`随时`在该页面的左下方点击`在 GitCode 上编辑此页`
![](./readme/readme-2.png)
### 2. 在 GitCode 校对/创作
进入GitCode之后,会自动定位到你想要修改的文件,修改文件内容。
#### 2-1. 仓库的成员
如果是仓库的成员,点击`“编辑”按钮,会直接进入可编辑的状态,供你修改文件内容。
![](./readme/readme-3.png)
![](./readme/readme-4.png)
#### 2-2. 非仓库的成员
如果是非仓库的成员,点击`“编辑”`,GitCode 会提醒你没有权限编辑,可以点击`Fork`按钮,将该项目克隆到你的 GitCode 账户下。
![](./readme/readme-5.png)
### 3. 内容编辑完成提交PR
内容编辑完成者向[此仓库](https://gitcode.net/dev-cloud/spring-docs)提交 PR(Pull Request)。
### 4. 审核
[主仓库](https://gitcode.net/dev-cloud/spring-docs) 管理者会 Review,符合要求的,即会 Merge 到[主仓库](https://gitcode.net/dev-cloud/spring-docs)中。
### 5. 查看更新
Merge 成功之后,稍等片刻就可以刷新页面查看更新。
此差异已折叠。
# Build Tool Plugins
Spring Boot provides build tool plugins for Maven and Gradle.
The plugins offer a variety of features, including the packaging of executable jars.
This section provides more details on both plugins as well as some help should you need to extend an unsupported build system.
If you are just getting started, you might want to read “[using.html](using.html#using.build-systems)” from the “[using.html](using.html#using)” section first.
## 1.1 Spring Boot Maven Plugin
The Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application “in-place”.
To use it, you must use Maven 3.2 (or later).
See the plugin’s documentation to learn more:
* Reference ([HTML](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/) and [PDF](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/pdf/spring-boot-maven-plugin-reference.pdf))
* [API](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/api/)
## 1.2. Spring Boot Gradle Plugin
The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, letting you package executable jar or war archives, run Spring Boot applications, and use the dependency management provided by `spring-boot-dependencies`.
It requires Gradle 6.8, 6.9, or 7.x.
See the plugin’s documentation to learn more:
* Reference ([HTML](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/) and [PDF](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/pdf/spring-boot-gradle-plugin-reference.pdf))
* [API](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/api/)
## 3. Spring Boot AntLib Module
The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant.
You can use the module to create executable jars.
To use the module, you need to declare an additional `spring-boot` namespace in your `build.xml`, as shown in the following example:
```
<project xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:spring-boot="antlib:org.springframework.boot.ant"
name="myapp" default="build">
...
</project>
```
You need to remember to start Ant using the `-lib` option, as shown in the following example:
```
$ ant -lib <directory containing spring-boot-antlib-2.6.4.jar>
```
> The “Using Spring Boot” section includes a more complete example of [using Apache Ant with `spring-boot-antlib`](using.html#using.build-systems.ant).
### 3.1. Spring Boot Ant Tasks
Once the `spring-boot-antlib` namespace has been declared, the following additional tasks are available:
* [Using the “exejar” Task](#build-tool-plugins.antlib.tasks.exejar)
* [Using the “findmainclass” Task](#build-tool-plugins.antlib.findmainclass)
#### 3.1.1. Using the “exejar” Task
You can use the `exejar` task to create a Spring Boot executable jar.
The following attributes are supported by the task:
| Attribute | Description | Required |
|-------------|--------------------------------------|-------------------------------------------------------------------------|
| `destfile` | The destination jar file to create | Yes |
| `classes` |The root directory of Java class files| Yes |
|`start-class`| The main application class to run |No *(the default is the first class found that declares a `main` method)*|
The following nested elements can be used with the task:
| Element | Description |
|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|`resources`|One or more [Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection) describing a set of [Resources](https://ant.apache.org/manual/Types/resources.html) that should be added to the content of the created jar file.|
| `lib` | One or more [Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection) that should be added to the set of jar libraries that make up the runtime dependency classpath of the application. |
#### 3.1.2. Examples
This section shows two examples of Ant tasks.
Specify start-class
```
<spring-boot:exejar destfile="target/my-application.jar"
classes="target/classes" start-class="com.example.MyApplication">
<resources>
<fileset dir="src/main/resources" />
</resources>
<lib>
<fileset dir="lib" />
</lib>
</spring-boot:exejar>
```
Detect start-class
```
<exejar destfile="target/my-application.jar" classes="target/classes">
<lib>
<fileset dir="lib" />
</lib>
</exejar>
```
### 3.2. Using the “findmainclass” Task
The `findmainclass` task is used internally by `exejar` to locate a class declaring a `main`.
If necessary, you can also use this task directly in your build.
The following attributes are supported:
| Attribute | Description | Required |
|-------------|----------------------------------------------------|-------------------------------------------|
|`classesroot`| The root directory of Java class files | Yes *(unless `mainclass` is specified)* |
| `mainclass` |Can be used to short-circuit the `main` class search| No |
| `property` |The Ant property that should be set with the result |No *(result will be logged if unspecified)*|
#### 3.2.1. Examples
This section contains three examples of using `findmainclass`.
Find and log
```
<findmainclass classesroot="target/classes" />
```
Find and set
```
<findmainclass classesroot="target/classes" property="main-class" />
```
Override and set
```
<findmainclass mainclass="com.example.MainClass" property="main-class" />
```
## 4. Supporting Other Build Systems
If you want to use a build tool other than Maven, Gradle, or Ant, you likely need to develop your own plugin.
Executable jars need to follow a specific format and certain entries need to be written in an uncompressed form (see the “[executable jar format](executable-jar.html#appendix.executable-jar)” section in the appendix for details).
The Spring Boot Maven and Gradle plugins both make use of `spring-boot-loader-tools` to actually generate jars.
If you need to, you may use this library directly.
### 4.1. Repackaging Archives
To repackage an existing archive so that it becomes a self-contained executable archive, use `org.springframework.boot.loader.tools.Repackager`.
The `Repackager` class takes a single constructor argument that refers to an existing jar or war archive.
Use one of the two available `repackage()` methods to either replace the original file or write to a new destination.
Various settings can also be configured on the repackager before it is run.
### 4.2. Nested Libraries
When repackaging an archive, you can include references to dependency files by using the `org.springframework.boot.loader.tools.Libraries` interface.
We do not provide any concrete implementations of `Libraries` here as they are usually build-system-specific.
If your archive already includes libraries, you can use `Libraries.NONE`.
### 4.3. Finding a Main Class
If you do not use `Repackager.setMainClass()` to specify a main class, the repackager uses [ASM](https://asm.ow2.io/) to read class files and tries to find a suitable class with a `public static void main(String[] args)` method.
An exception is thrown if more than one candidate is found.
### 4.4. Example Repackage Implementation
The following example shows a typical repackage implementation:
```
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.springframework.boot.loader.tools.Library;
import org.springframework.boot.loader.tools.LibraryCallback;
import org.springframework.boot.loader.tools.LibraryScope;
import org.springframework.boot.loader.tools.Repackager;
public class MyBuildTool {
public void build() throws IOException {
File sourceJarFile = ...
Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(false);
repackager.repackage(this::getLibraries);
}
private void getLibraries(LibraryCallback callback) throws IOException {
// Build system specific implementation, callback for each dependency
for (File nestedJar : getCompileScopeJars()) {
callback.library(new Library(nestedJar, LibraryScope.COMPILE));
}
// ...
}
private List<File> getCompileScopeJars() {
return ...
}
}
```
## 5. What to Read Next
If you are interested in how the build tool plugins work, you can look at the [`spring-boot-tools`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-tools) module on GitHub.
More technical details of the executable jar format are covered in [the appendix](executable-jar.html#appendix.executable-jar).
If you have specific build-related questions, see the “[how-to](howto.html#howto)” guides.
# Spring Boot CLI
The Spring Boot CLI is a command line tool that you can use if you want to quickly develop a Spring application.
It lets you run Groovy scripts, which means that you have a familiar Java-like syntax without so much boilerplate code.
You can also bootstrap a new project or write your own command for it.
## 1. Installing the CLI
The Spring Boot CLI (Command-Line Interface) can be installed manually by using SDKMAN! (the SDK Manager) or by using Homebrew or MacPorts if you are an OSX user.
See *[getting-started.html](getting-started.html#getting-started.installing.cli)* in the “Getting started” section for comprehensive installation instructions.
## 2. Using the CLI
Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at the command line.
If you run `spring` without any arguments, a help screen is displayed, as follows:
```
$ spring
usage: spring [--help] [--version]
<command> [<args>]
Available commands are:
run [options] <files> [--] [args]
Run a spring groovy script
_... more command help is shown here_
```
You can type `spring help` to get more details about any of the supported commands, as shown in the following example:
```
$ spring help run
spring run - Run a spring groovy script
usage: spring run [options] <files> [--] [args]
Option Description
------ -----------
--autoconfigure [Boolean] Add autoconfigure compiler
transformations (default: true)
--classpath, -cp Additional classpath entries
--no-guess-dependencies Do not attempt to guess dependencies
--no-guess-imports Do not attempt to guess imports
-q, --quiet Quiet logging
-v, --verbose Verbose logging of dependency
resolution
--watch Watch the specified file for changes
```
The `version` command provides a quick way to check which version of Spring Boot you are using, as follows:
```
$ spring version
Spring CLI v2.6.4
```
### 2.1. Running Applications with the CLI
You can compile and run Groovy source code by using the `run` command.
The Spring Boot CLI is completely self-contained, so you do not need any external Groovy installation.
The following example shows a “hello world” web application written in Groovy:
hello.groovy
```
@RestController
class WebApplication {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
```
To compile and run the application, type the following command:
```
$ spring run hello.groovy
```
To pass command-line arguments to the application, use `--` to separate the commands from the “spring” command arguments, as shown in the following example:
```
$ spring run hello.groovy -- --server.port=9000
```
To set JVM command line arguments, you can use the `JAVA_OPTS` environment variable, as shown in the following example:
```
$ JAVA_OPTS=-Xmx1024m spring run hello.groovy
```
| |When setting `JAVA_OPTS` on Microsoft Windows, make sure to quote the entire instruction, such as `set "JAVA_OPTS=-Xms256m -Xmx2048m"`.<br/>Doing so ensures the values are properly passed to the process.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.1. Deduced “grab” Dependencies
Standard Groovy includes a `@Grab` annotation, which lets you declare dependencies on third-party libraries.
This useful technique lets Groovy download jars in the same way as Maven or Gradle would but without requiring you to use a build tool.
Spring Boot extends this technique further and tries to deduce which libraries to “grab” based on your code.
For example, since the `WebApplication` code shown previously uses `@RestController` annotations, Spring Boot grabs "Tomcat" and "Spring MVC".
The following items are used as “grab hints”:
| Items | Grabs |
|----------------------------------------------------------|------------------------------|
|`JdbcTemplate`, `NamedParameterJdbcTemplate`, `DataSource`| JDBC Application. |
| `@EnableJms` | JMS Application. |
| `@EnableCaching` | Caching abstraction. |
| `@Test` | JUnit. |
| `@EnableRabbit` | RabbitMQ. |
| extends `Specification` | Spock test. |
| `@EnableBatchProcessing` | Spring Batch. |
| `@MessageEndpoint` `@EnableIntegration` | Spring Integration. |
| `@Controller` `@RestController` `@EnableWebMvc` |Spring MVC + Embedded Tomcat. |
| `@EnableWebSecurity` | Spring Security. |
| `@EnableTransactionManagement` |Spring Transaction Management.|
| |See subclasses of [`CompilerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java) in the Spring Boot CLI source code to understand exactly how customizations are applied.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.2. Deduced “grab” Coordinates
Spring Boot extends Groovy’s standard `@Grab` support by letting you specify a dependency without a group or version (for example, `@Grab('freemarker')`).
Doing so consults Spring Boot’s default dependency metadata to deduce the artifact’s group and version.
| |The default metadata is tied to the version of the CLI that you use.<br/>It changes only when you move to a new version of the CLI, putting you in control of when the versions of your dependencies may change.<br/>A table showing the dependencies and their versions that are included in the default metadata can be found in the [appendix](dependency-versions.html#appendix.dependency-versions).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.3. Default Import Statements
To help reduce the size of your Groovy code, several `import` statements are automatically included.
Notice how the preceding example refers to `@Component`, `@RestController`, and `@RequestMapping` without needing to use fully-qualified names or `import` statements.
| |Many Spring annotations work without using `import` statements.<br/>Try running your application to see what fails before adding imports.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.4. Automatic Main Method
Unlike the equivalent Java application, you do not need to include a `public static void main(String[] args)` method with your `Groovy` scripts.
A `SpringApplication` is automatically created, with your compiled code acting as the `source`.
#### 2.1.5. Custom Dependency Management
By default, the CLI uses the dependency management declared in `spring-boot-dependencies` when resolving `@Grab` dependencies.
Additional dependency management, which overrides the default dependency management, can be configured by using the `@DependencyManagementBom` annotation.
The annotation’s value should specify the coordinates (`groupId:artifactId:version`) of one or more Maven BOMs.
For example, consider the following declaration:
```
@DependencyManagementBom("com.example.custom-bom:1.0.0")
```
The preceding declaration picks up `custom-bom-1.0.0.pom` in a Maven repository under `com/example/custom-versions/1.0.0/`.
When you specify multiple BOMs, they are applied in the order in which you declare them, as shown in the following example:
```
@DependencyManagementBom([
"com.example.custom-bom:1.0.0",
"com.example.another-bom:1.0.0"])
```
The preceding example indicates that the dependency management in `another-bom` overrides the dependency management in `custom-bom`.
You can use `@DependencyManagementBom` anywhere that you can use `@Grab`.
However, to ensure consistent ordering of the dependency management, you can use `@DependencyManagementBom` at most once in your application.
### 2.2. Applications with Multiple Source Files
You can use “shell globbing” with all commands that accept file input.
Doing so lets you use multiple files from a single directory, as shown in the following example:
```
$ spring run *.groovy
```
### 2.3. Packaging Your Application
You can use the `jar` command to package your application into a self-contained executable jar file, as shown in the following example:
```
$ spring jar my-app.jar *.groovy
```
The resulting jar contains the classes produced by compiling the application and all of the application’s dependencies so that it can then be run by using `java -jar`.
The jar file also contains entries from the application’s classpath.
You can add and remove explicit paths to the jar by using `--include` and `--exclude`.
Both are comma-separated, and both accept prefixes, in the form of “+” and “-”, to signify that they should be removed from the defaults.
The default includes are as follows:
```
public/**, resources/**, static/**, templates/**, META-INF/**, *
```
The default excludes are as follows:
```
.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy
```
Type `spring help jar` on the command line for more information.
### 2.4. Initialize a New Project
The `init` command lets you create a new project by using [start.spring.io](https://start.spring.io) without leaving the shell, as shown in the following example:
```
$ spring init --dependencies=web,data-jpa my-project
Using service at https://start.spring.io
Project extracted to '/Users/developer/example/my-project'
```
The preceding example creates a `my-project` directory with a Maven-based project that uses `spring-boot-starter-web` and `spring-boot-starter-data-jpa`.
You can list the capabilities of the service by using the `--list` flag, as shown in the following example:
```
$ spring init --list
=======================================
Capabilities of https://start.spring.io
=======================================
Available dependencies:
-----------------------
actuator - Actuator: Production ready features to help you monitor and manage your application
...
web - Web: Support for full-stack web development, including Tomcat and spring-webmvc
websocket - Websocket: Support for WebSocket development
ws - WS: Support for Spring Web Services
Available project types:
------------------------
gradle-build - Gradle Config [format:build, build:gradle]
gradle-project - Gradle Project [format:project, build:gradle]
maven-build - Maven POM [format:build, build:maven]
maven-project - Maven Project [format:project, build:maven] (default)
...
```
The `init` command supports many options.
See the `help` output for more details.
For instance, the following command creates a Gradle project that uses Java 8 and `war` packaging:
```
$ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip
Using service at https://start.spring.io
Content saved to 'sample-app.zip'
```
### 2.5. Using the Embedded Shell
Spring Boot includes command-line completion scripts for the BASH and zsh shells.
If you do not use either of these shells (perhaps you are a Windows user), you can use the `shell` command to launch an integrated shell, as shown in the following example:
```
$ spring shell
Spring Boot (v2.6.4)
Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit.
```
From inside the embedded shell, you can run other commands directly:
```
$ version
Spring CLI v2.6.4
```
The embedded shell supports ANSI color output as well as `tab` completion.
If you need to run a native command, you can use the `!` prefix.
To exit the embedded shell, press `ctrl-c`.
### 2.6. Adding Extensions to the CLI
You can add extensions to the CLI by using the `install` command.
The command takes one or more sets of artifact coordinates in the format `group:artifact:version`, as shown in the following example:
```
$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE
```
In addition to installing the artifacts identified by the coordinates you supply, all of the artifacts' dependencies are also installed.
To uninstall a dependency, use the `uninstall` command.
As with the `install` command, it takes one or more sets of artifact coordinates in the format of `group:artifact:version`, as shown in the following example:
```
$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE
```
It uninstalls the artifacts identified by the coordinates you supply and their dependencies.
To uninstall all additional dependencies, you can use the `--all` option, as shown in the following example:
```
$ spring uninstall --all
```
## 3. Developing Applications with the Groovy Beans DSL
Spring Framework 4.0 has native support for a `beans{}` “DSL” (borrowed from [Grails](https://grails.org/)), and you can embed bean definitions in your Groovy application scripts by using the same format.
This is sometimes a good way to include external features like middleware declarations, as shown in the following example:
```
@Configuration(proxyBeanMethods = false)
class Application implements CommandLineRunner {
@Autowired
SharedService service
@Override
void run(String... args) {
println service.message
}
}
import my.company.SharedService
beans {
service(SharedService) {
message = "Hello World"
}
}
```
You can mix class declarations with `beans{}` in the same file as long as they stay at the top level, or, if you prefer, you can put the beans DSL in a separate file.
## 4. Configuring the CLI with settings.xml
The Spring Boot CLI uses Maven Resolver, Maven’s dependency resolution engine, to resolve dependencies.
The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` to configure Maven Resolver.
The following configuration settings are honored by the CLI:
* Offline
* Mirrors
* Servers
* Proxies
* Profiles
* Activation
* Repositories
* Active profiles
See [Maven’s settings documentation](https://maven.apache.org/settings.html) for further information.
## 5. What to Read Next
There are some [sample groovy scripts](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/samples) available from the GitHub repository that you can use to try out the Spring Boot CLI.
There is also extensive Javadoc throughout the [source code](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli).
If you find that you reach the limit of the CLI tool, you probably want to look at converting your application to a full Gradle or Maven built “Groovy project”.
The next section covers Spring Boot’s "[Build tool plugins](build-tool-plugins.html#build-tool-plugins)", which you can use with Gradle or Maven.
# Container Images
Spring Boot applications can be containerized [using Dockerfiles](#container-images.dockerfiles), or by [using Cloud Native Buildpacks to create optimized docker compatible container images that you can run anywhere](#container-images.buildpacks).
## 1. Efficient container images
It is easily possible to package a Spring Boot fat jar as a docker image.
However, there are various downsides to copying and running the fat jar as is in the docker image.
There’s always a certain amount of overhead when running a fat jar without unpacking it, and in a containerized environment this can be noticeable.
The other issue is that putting your application’s code and all its dependencies in one layer in the Docker image is sub-optimal.
Since you probably recompile your code more often than you upgrade the version of Spring Boot you use, it’s often better to separate things a bit more.
If you put jar files in the layer before your application classes, Docker often only needs to change the very bottom layer and can pick others up from its cache.
### 1.1. Unpacking the fat jar
If you are running your application from a container, you can use an executable jar, but it is also often an advantage to explode it and run it in a different way.
Certain PaaS implementations may also choose to unpack archives before they run.
For example, Cloud Foundry operates this way.
One way to run an unpacked archive is by starting the appropriate launcher, as follows:
```
$ jar -xf myapp.jar
$ java org.springframework.boot.loader.JarLauncher
```
This is actually slightly faster on startup (depending on the size of the jar) than running from an unexploded archive.
At runtime you should not expect any differences.
Once you have unpacked the jar file, you can also get an extra boost to startup time by running the app with its "natural" main method instead of the `JarLauncher`. For example:
```
$ jar -xf myapp.jar
$ java -cp BOOT-INF/classes:BOOT-INF/lib/* com.example.MyApplication
```
| |Using the `JarLauncher` over the application’s main method has the added benefit of a predictable classpath order.<br/>The jar contains a `classpath.idx` file which is used by the `JarLauncher` when constructing the classpath.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
### 1.2. Layering Docker Images
To make it easier to create optimized Docker images, Spring Boot supports adding a layer index file to the jar.
It provides a list of layers and the parts of the jar that should be contained within them.
The list of layers in the index is ordered based on the order in which the layers should be added to the Docker/OCI image.
Out-of-the-box, the following layers are supported:
* `dependencies` (for regular released dependencies)
* `spring-boot-loader` (for everything under `org/springframework/boot/loader`)
* `snapshot-dependencies` (for snapshot dependencies)
* `application` (for application classes and resources)
The following shows an example of a `layers.idx` file:
```
- "dependencies":
- BOOT-INF/lib/library1.jar
- BOOT-INF/lib/library2.jar
- "spring-boot-loader":
- org/springframework/boot/loader/JarLauncher.class
- org/springframework/boot/loader/jar/JarEntry.class
- "snapshot-dependencies":
- BOOT-INF/lib/library3-SNAPSHOT.jar
- "application":
- META-INF/MANIFEST.MF
- BOOT-INF/classes/a/b/C.class
```
This layering is designed to separate code based on how likely it is to change between application builds.
Library code is less likely to change between builds, so it is placed in its own layers to allow tooling to re-use the layers from cache.
Application code is more likely to change between builds so it is isolated in a separate layer.
Spring Boot also supports layering for war files with the help of a `layers.idx`.
For Maven, see the [packaging layered jar or war section](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#repackage-layers) for more details on adding a layer index to the archive.
For Gradle, see the [packaging layered jar or war section](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#packaging-layered-archives) of the Gradle plugin documentation.
## 2. Dockerfiles
While it is possible to convert a Spring Boot fat jar into a docker image with just a few lines in the Dockerfile, we will use the [layering feature](#container-images.efficient-images.layering) to create an optimized docker image.
When you create a jar containing the layers index file, the `spring-boot-jarmode-layertools` jar will be added as a dependency to your jar.
With this jar on the classpath, you can launch your application in a special mode which allows the bootstrap code to run something entirely different from your application, for example, something that extracts the layers.
| |The `layertools` mode can not be used with a [fully executable Spring Boot archive](deployment.html#deployment.installing) that includes a launch script.<br/>Disable launch script configuration when building a jar file that is intended to be used with `layertools`.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
Here’s how you can launch your jar with a `layertools` jar mode:
```
$ java -Djarmode=layertools -jar my-app.jar
```
This will provide the following output:
```
Usage:
java -Djarmode=layertools -jar my-app.jar
Available commands:
list List layers from the jar that can be extracted
extract Extracts layers from the jar for image creation
help Help about any command
```
The `extract` command can be used to easily split the application into layers to be added to the dockerfile.
Here is an example of a Dockerfile using `jarmode`.
```
FROM adoptopenjdk:11-jre-hotspot as builder
WORKDIR application
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract
FROM adoptopenjdk:11-jre-hotspot
WORKDIR application
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
```
Assuming the above `Dockerfile` is in the current directory, your docker image can be built with `docker build .`, or optionally specifying the path to your application jar, as shown in the following example:
```
$ docker build --build-arg JAR_FILE=path/to/myapp.jar .
```
This is a multi-stage dockerfile.
The builder stage extracts the directories that are needed later.
Each of the `COPY` commands relates to the layers extracted by the jarmode.
Of course, a Dockerfile can be written without using the jarmode.
You can use some combination of `unzip` and `mv` to move things to the right layer but jarmode simplifies that.
## 3. Cloud Native Buildpacks
Dockerfiles are just one way to build docker images.
Another way to build docker images is directly from your Maven or Gradle plugin, using buildpacks.
If you’ve ever used an application platform such as Cloud Foundry or Heroku then you’ve probably used a buildpack.
Buildpacks are the part of the platform that takes your application and converts it into something that the platform can actually run.
For example, Cloud Foundry’s Java buildpack will notice that you’re pushing a `.jar` file and automatically add a relevant JRE.
With Cloud Native Buildpacks, you can create Docker compatible images that you can run anywhere.
Spring Boot includes buildpack support directly for both Maven and Gradle.
This means you can just type a single command and quickly get a sensible image into your locally running Docker daemon.
See the individual plugin documentation on how to use buildpacks with [Maven](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#build-image) and [Gradle](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#build-image).
| |The [Paketo Spring Boot buildpack](https://github.com/paketo-buildpacks/spring-boot) has also been updated to support the `layers.idx` file so any customization that is applied to it will be reflected in the image created by the buildpack.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| |In order to achieve reproducible builds and container image caching, Buildpacks can manipulate the application resources metadata (such as the file "last modified" information).<br/>You should ensure that your application does not rely on that metadata at runtime.<br/>Spring Boot can use that information when serving static resources, but this can be disabled with `spring.web.resources.cache.use-last-modified`|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
## 4. What to Read Next
Once you’ve learned how to build efficient container images, you can read about [deploying applications to a cloud platform](deployment.html#deployment.cloud.kubernetes), such as Kubernetes.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Getting Help
If you have trouble with Spring Boot, we would like to help.
* Try the [How-to documents](howto.html#howto).
They provide solutions to the most common questions.
* Learn the Spring basics.
Spring Boot builds on many other Spring projects.
Check the [spring.io](https://spring.io) web-site for a wealth of reference documentation.
If you are starting out with Spring, try one of the [guides](https://spring.io/guides).
* Ask a question.
We monitor [stackoverflow.com](https://stackoverflow.com) for questions tagged with [`spring-boot`](https://stackoverflow.com/tags/spring-boot).
* Report bugs with Spring Boot at [github.com/spring-projects/spring-boot/issues](https://github.com/spring-projects/spring-boot/issues).
Note:
All of Spring Boot is open source, including the documentation. If you find problems with the docs or if you want to improve them, please [get involved](https://github.com/spring-projects/spring-boot/tree/v2.6.4).
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Legal
Copyright © 2012-2022
Copies of this document may be made for your own use and for distribution to
others, provided that you do not charge any fee for such copies and further
provided that each copy contains this Copyright Notice, whether distributed in
print or electronically.
此差异已折叠。
# Upgrading Spring Boot
Instructions for how to upgrade from earlier versions of Spring Boot are provided on the project [wiki](https://github.com/spring-projects/spring-boot/wiki).
Follow the links in the [release notes](https://github.com/spring-projects/spring-boot/wiki#release-notes) section to find the version that you want to upgrade to.
Upgrading instructions are always the first item in the release notes.
If you are more than one release behind, please make sure that you also review the release notes of the versions that you jumped.
## 1. Upgrading from 1.x
If you are upgrading from the `1.x` release of Spring Boot, check the [“migration guide” on the project wiki](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide) that provides detailed upgrade instructions.
Check also the [“release notes”](https://github.com/spring-projects/spring-boot/wiki) for a list of “new and noteworthy” features for each release.
## 2. Upgrading to a new feature release
When upgrading to a new feature release, some properties may have been renamed or removed.
Spring Boot provides a way to analyze your application’s environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you.
To enable that feature, add the following dependency to your project:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
```
| |Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account.|
|---|------------------------------------------------------------------------------------------------------------------------|
| |Once you finish the migration, please make sure to remove this module from your project’s dependencies.|
|---|-------------------------------------------------------------------------------------------------------|
## 3. Upgrading the Spring Boot CLI
To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`).
If you manually installed the CLI, follow the [standard instructions](getting-started.html#getting-started.installing.cli.manual-installation), remembering to update your `PATH` environment variable to remove any older references.
## 4. What to Read Next
Once you’ve decided to upgrade your application, you can find detailed information regarding specific features in the rest of the document.
Spring Boot’s documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version.
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Spring Cloud
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Spring Cloud Contract Reference Documentation
Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
The reference documentation consists of the following sections:
| [Legal](legal.html#legal-information) | Legal information. |
|----------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|
|[Documentation Overview](documentation-overview.html#contract-documentation)| About the Documentation, Getting Help, First Steps, and more. |
| [Getting Started](getting-started.html#getting-started) |Introducing Spring Cloud Contract, Developing Your First Spring Cloud Contract-based Application|
| [Using Spring Cloud Contract](using.html#using) | Spring Cloud Contract usage examples and workflows. |
| [Spring Cloud Contract Features](project-features.html#features) |Contract DSL, Messaging, Spring Cloud Contract Stub Runner, and Spring Cloud Contract WireMock. |
| [Build Tools](project-features.html#features-build-tools) | Maven Plugin, Gradle Plugin, and Docker. |
| [“How-to” Guides](howto.html#howto) | Stubs versioning, Pact integration, Debugging, and more. |
| [Appendices](appendix.html#appendix) | Properties, Metadata, Configuration, Dependencies, and more. |
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Spring Data
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册