提交 5b885824 编写于 作者: M Mao

Merge branch 'structrue' into MaoXianxin

Build Tool Plugins
==========
Table of Contents
[Back to index](index.html)
* [1. Spring Boot Maven Plugin](#build-tool-plugins.maven)
* [2. Spring Boot Gradle Plugin](#build-tool-plugins.gradle)
* [3. Spring Boot AntLib Module](#build-tool-plugins.antlib)
* [3.1. Spring Boot Ant Tasks](#build-tool-plugins.antlib.tasks)
* [3.1.1. Using the “exejar” Task](#build-tool-plugins.antlib.tasks.exejar)
* [3.1.2. Examples](#build-tool-plugins.antlib.tasks.examples)
* [3.2. Using the “findmainclass” Task](#build-tool-plugins.antlib.findmainclass)
* [3.2.1. Examples](#build-tool-plugins.antlib.findmainclass.examples)
* [4. Supporting Other Build Systems](#build-tool-plugins.other-build-systems)
* [4.1. Repackaging Archives](#build-tool-plugins.other-build-systems.repackaging-archives)
* [4.2. Nested Libraries](#build-tool-plugins.other-build-systems.nested-libraries)
* [4.3. Finding a Main Class](#build-tool-plugins.other-build-systems.finding-main-class)
* [4.4. Example Repackage Implementation](#build-tool-plugins.other-build-systems.example-repackage-implementation)
* [5. What to Read Next](#build-tool-plugins.whats-next)
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.
[](#build-tool-plugins.maven)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/)
[](#build-tool-plugins.gradle)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/)
[](#build-tool-plugins.antlib)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).|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------|
### [](#build-tool-plugins.antlib.tasks)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)
#### [](#build-tool-plugins.antlib.tasks.exejar)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. |
#### [](#build-tool-plugins.antlib.tasks.examples)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>
```
### [](#build-tool-plugins.antlib.findmainclass)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)*|
#### [](#build-tool-plugins.antlib.findmainclass.examples)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" />
```
[](#build-tool-plugins.other-build-systems)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.
### [](#build-tool-plugins.other-build-systems.repackaging-archives)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.
### [](#build-tool-plugins.other-build-systems.nested-libraries)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`.
### [](#build-tool-plugins.other-build-systems.finding-main-class)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.
### [](#build-tool-plugins.other-build-systems.example-repackage-implementation)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 ...
}
}
```
[](#build-tool-plugins.whats-next)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.
Container Images
==========
Table of Contents
[Back to index](index.html)
* [1. Efficient container images](#container-images.efficient-images)
* [1.1. Unpacking the fat jar](#container-images.efficient-images.unpacking)
* [1.2. Layering Docker Images](#container-images.efficient-images.layering)
* [2. Dockerfiles](#container-images.dockerfiles)
* [3. Cloud Native Buildpacks](#container-images.buildpacks)
* [4. What to Read Next](#container-images.whats-next)
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).
[](#container-images.efficient-images)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.
### [](#container-images.efficient-images.unpacking)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.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
### [](#container-images.efficient-images.layering)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.
[](#container-images.dockerfiles)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.
[](#container-images.buildpacks)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`|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
[](#container-images.whats-next)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.
此差异已折叠。
此差异已折叠。
Documentation Overview
==========
Table of Contents
[Back to index](index.html)
* [1. First Steps](#documentation.first-steps)
* [2. Upgrading From an Earlier Version](#documentation.upgrading)
* [3. Developing with Spring Boot](#documentation.using)
* [4. Learning About Spring Boot Features](#documentation.features)
* [5. Web](#documentation.web)
* [6. Data](#documentation.data)
* [7. Messaging](#documentation.messaging)
* [8. IO](#documentation.io)
* [9. Container Images](#documentation.container-images)
* [10. Advanced Topics](#documentation.advanced)
This section provides a brief overview of Spring Boot reference documentation.
It serves as a map for the rest of the document.
The latest copy of this document is available at [docs.spring.io/spring-boot/docs/current/reference/](https://docs.spring.io/spring-boot/docs/current/reference/).
[](#documentation.first-steps)1. First Steps
----------
If you are getting started with Spring Boot or 'Spring' in general, start with [the following topics](getting-started.html#getting-started):
* **From scratch:** [Overview](getting-started.html#getting-started.introducing-spring-boot) | [Requirements](getting-started.html#getting-started.system-requirements) | [Installation](getting-started.html#getting-started.installing)
* **Tutorial:** [Part 1](getting-started.html#getting-started.first-application) | [Part 2](getting-started.html#getting-started.first-application.code)
* **Running your example:** [Part 1](getting-started.html#getting-started.first-application.run) | [Part 2](getting-started.html#getting-started.first-application.executable-jar)
[](#documentation.upgrading)2. Upgrading From an Earlier Version
----------
You should always ensure that you are running a [supported version](https://github.com/spring-projects/spring-boot/wiki/Supported-Versions) of Spring Boot.
Depending on the version that you are upgrading to, you can find some additional tips here:
* **From 1.x:** [Upgrading from 1.x](actuator.html#upgrading.from-1x)
* **To a new feature release:** [Upgrading to New Feature Release](upgrading.html#upgrading.to-feature)
* **Spring Boot CLI:** [Upgrading the Spring Boot CLI](upgrading.html#upgrading.cli)
[](#documentation.using)3. Developing with Spring Boot
----------
Ready to actually start using Spring Boot? [We have you covered](using.html#using):
* **Build systems:** [Maven](using.html#using.build-systems.maven) | [Gradle](using.html#using.build-systems.gradle) | [Ant](using.html#using.build-systems.ant) | [Starters](using.html#using.build-systems.starters)
* **Best practices:** [Code Structure](using.html#using.structuring-your-code) | [@Configuration](using.html#using.configuration-classes) | [@EnableAutoConfiguration](using.html#using.auto-configuration) | [Beans and Dependency Injection](using.html#using.spring-beans-and-dependency-injection)
* **Running your code:** [IDE](using.html#using.running-your-application.from-an-ide) | [Packaged](using.html#using.running-your-application.as-a-packaged-application) | [Maven](using.html#using.running-your-application.with-the-maven-plugin) | [Gradle](using.html#using.running-your-application.with-the-gradle-plugin)
* **Packaging your app:** [Production jars](using.html#using.packaging-for-production)
* **Spring Boot CLI:** [Using the CLI](cli.html#cli)
[](#documentation.features)4. Learning About Spring Boot Features
----------
Need more details about Spring Boot’s core features?[The following content is for you](features.html#features):
* **Spring Application:** [SpringApplication](features.html#features.spring-application)
* **External Configuration:** [External Configuration](features.html#features.external-config)
* **Profiles:** [Profiles](features.html#features.profiles)
* **Logging:** [Logging](features.html#features.logging)
[](#documentation.web)5. Web
----------
If you develop Spring Boot web applications, take a look at the following content:
* **Servlet Web Applications:** [Spring MVC, Jersey, Embedded Servlet Containers](web.html#web.servlet)
* **Reactive Web Applications:** [Spring Webflux, Embedded Servlet Containers](web.html#web.reactive)
* **Graceful Shutdown:** [Graceful Shutdown](web.html#web.graceful-shutdown)
* **Spring Security:** [Default Security Configuration, Auto-configuration for OAuth2, SAML](web.html#web.security)
* **Spring Session:** [Auto-configuration for Spring Session](web.html#web.spring-session)
* **Spring HATEOAS:** [Auto-configuration for Spring HATEOAS](web.html#web.spring-hateoas)
[](#documentation.data)6. Data
----------
If your application deals with a datastore, you can see how to configure that here:
* **SQL:** [Configuring a SQL Datastore, Embedded Database support, Connection pools, and more.](data.html#data.sql)
* **NOSQL:** [Auto-configuration for NOSQL stores such as Redis, MongoDB, Neo4j, and others.](data.html#data.nosql)
[](#documentation.messaging)7. Messaging
----------
If your application uses any messaging protocol, see one or more of the following sections:
* **JMS:** [Auto-configuration for ActiveMQ and Artemis, Sending and Receiving messages through JMS](messaging.html#messaging.jms)
* **AMQP:** [Auto-configuration for RabbitMQ](messaging.html#messaging.amqp)
* **Kafka:** [Auto-configuration for Spring Kafka](messaging.html#messaging.kafka)
* **RSocket:** [Auto-configuration for Spring Framework’s RSocket Support](messaging.html#messaging.rsocket)
* **Spring Integration:** [Auto-configuration for Spring Integration](messaging.html#messaging.spring-integration)
[](#documentation.io)8. IO
----------
If your application needs IO capabilities, see one or more of the following sections:
* **Caching:** [Caching support EhCache, Hazelcast, Infinispan and more](io.html#io.caching)
* **Quartz:** [Quartz Scheduling](io.html#io.quartz)
* **Mail:** [Sending Email](io.html#io.email)
* **Validation:** [JSR-303 Validation](io.html#io.validation)
* **REST Clients:** [Calling REST Services with RestTemplate and WebClient](io.html#io.rest-client)
* **Webservices:** [Auto-configuration for Spring Web Services](io.html#io.webservices)
* **JTA:** [Distributed Transactions with JTA](io.html#io.jta)
[](#documentation.container-images)9. Container Images
----------
Spring Boot provides first-class support for building efficient container images. You can read more about it here:
* **Efficient Container Images:** [Tips to optimize container images such as Docker images](container-images.html#container-images.efficient-images)
* **Dockerfiles:** [Building container images using dockerfiles](container-images.html#container-images.dockerfiles)
* **Cloud Native Buildpacks:** [Support for Cloud Native Buildpacks with Maven and Gradle](container-images.html#container-images.buildpacks)
[](#documentation.advanced)10. Advanced Topics
----------
Finally, we have a few topics for more advanced users:
* **Spring Boot Applications Deployment:** [Cloud Deployment](deployment.html#deployment.cloud) | [OS Service](deployment.html#deployment.installing.nix-services)
* **Build tool plugins:** [Maven](build-tool-plugins.html#build-tool-plugins.maven) | [Gradle](build-tool-plugins.html#build-tool-plugins.gradle)
* **Appendix:** [Application Properties](application-properties.html#appendix.application-properties) | [Configuration Metadata](configuration-metadata.html#appendix.configuration-metadata) | [Auto-configuration Classes](auto-configuration-classes.html#appendix.auto-configuration-classes) | [Test Auto-configuration Annotations](test-auto-configuration.html#appendix.test-auto-configuration) | [Executable Jars](executable-jar.html#appendix.executable-jar) | [Dependency Versions](dependency-versions.html#appendix.dependency-versions)
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.
此差异已折叠。
此差异已折叠。
Spring Boot CLI
==========
Table of Contents
[Back to index](index.html)
* [1. Installing the CLI](#cli.installation)
* [2. Using the CLI](#cli.using-the-cli)
* [2.1. Running Applications with the CLI](#cli.using-the-cli.run)
* [2.1.1. Deduced “grab” Dependencies](#cli.using-the-cli.run.deduced-grab-annotations)
* [2.1.2. Deduced “grab” Coordinates](#cli.using-the-cli.run.deduced-grab-coordinates)
* [2.1.3. Default Import Statements](#cli.using-the-cli.run.default-import-statements)
* [2.1.4. Automatic Main Method](#cli.using-the-cli.run.automatic-main-method)
* [2.1.5. Custom Dependency Management](#cli.using-the-cli.run.custom-dependency-management)
* [2.2. Applications with Multiple Source Files](#cli.using-the-cli.multiple-source-files)
* [2.3. Packaging Your Application](#cli.using-the-cli.packaging)
* [2.4. Initialize a New Project](#cli.using-the-cli.initialize-new-project)
* [2.5. Using the Embedded Shell](#cli.using-the-cli.embedded-shell)
* [2.6. Adding Extensions to the CLI](#cli.using-the-cli.extensions)
* [3. Developing Applications with the Groovy Beans DSL](#cli.groovy-beans-dsl)
* [4. Configuring the CLI with settings.xml](#cli.maven-setting)
* [5. What to Read Next](#cli.whats-next)
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.
[](#cli.installation)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.
[](#cli.using-the-cli)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
```
### [](#cli.using-the-cli.run)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.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### [](#cli.using-the-cli.run.deduced-grab-annotations)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.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### [](#cli.using-the-cli.run.deduced-grab-coordinates)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).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### [](#cli.using-the-cli.run.default-import-statements)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.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------|
#### [](#cli.using-the-cli.run.automatic-main-method)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`.
#### [](#cli.using-the-cli.run.custom-dependency-management)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.
### [](#cli.using-the-cli.multiple-source-files)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
```
### [](#cli.using-the-cli.packaging)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.
### [](#cli.using-the-cli.initialize-new-project)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'
```
### [](#cli.using-the-cli.embedded-shell)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`.
### [](#cli.using-the-cli.extensions)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
```
[](#cli.groovy-beans-dsl)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.
[](#cli.maven-setting)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.
[](#cli.whats-next)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.
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册