Port the build to Gradle

Closes gh-19609
Closes gh-19608
This commit is contained in:
Andy Wilkinson
2020-01-10 13:48:43 +00:00
parent abe95fa8a7
commit ce99db1902
974 changed files with 17108 additions and 26596 deletions

View File

@@ -0,0 +1,78 @@
:numbered!:
[appendix]
[[common-application-properties]]
= Common Application properties
include::attributes.adoc[]
Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches.
This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume them.
TIP: Spring Boot provides various conversion mechanism with advanced value formatting, make sure to review <<spring-boot-features.adoc#boot-features-external-config-conversion, the properties conversion section>>.
NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
Also, you can define your own properties.
== Core properties
include::config-docs/core.adoc[]
== Cache properties
include::config-docs/cache.adoc[]
== Mail properties
include::config-docs/mail.adoc[]
== JSON properties
include::config-docs/json.adoc[]
== Data properties
include::config-docs/data.adoc[]
== Transaction properties
include::config-docs/transaction.adoc[]
== Data migration properties
include::config-docs/data-migration.adoc[]
== Integration properties
include::config-docs/integration.adoc[]
== Web properties
include::config-docs/web.adoc[]
== Templating properties
include::config-docs/templating.adoc[]
== Server properties
include::config-docs/server.adoc[]
== Security properties
include::config-docs/security.adoc[]
== RSocket properties
include::config-docs/rsocket.adoc[]
== Actuator properties
include::config-docs/actuator.adoc[]
== Devtools properties
include::config-docs/devtools.adoc[]
== Testing properties
include::config-docs/testing.adoc[]

View File

@@ -0,0 +1,24 @@
[appendix]
[[auto-configuration-classes]]
= Auto-configuration Classes
include::attributes.adoc[]
This appendix contains details of all of the auto-configuration classes provided by Spring Boot, with links to documentation and source code.
Remember to also look at the conditions report in your application for more details of which features are switched on.
(To do so, start the app with `--debug` or `-Ddebug` or, in an Actuator application, use the `conditions` endpoint).
[[auto-configuration-classes-from-autoconfigure-module]]
== `spring-boot-autoconfigure`
The following auto-configuration classes are from the `spring-boot-autoconfigure` module:
include::auto-configuration-classes/spring-boot-autoconfigure.adoc[]
[[auto-configuration-classes-from-actuator]]
== `spring-boot-actuator-autoconfigure`
The following auto-configuration classes are from the `spring-boot-actuator-autoconfigure` module:
include::auto-configuration-classes/spring-boot-actuator-autoconfigure.adoc[]

View File

@@ -0,0 +1,860 @@
[appendix]
[[configuration-metadata]]
= Configuration Metadata
include::attributes.adoc[]
Spring Boot jars include metadata files that provide details of all supported configuration properties.
The files are designed to let IDE developers offer contextual help and "`code completion`" as users are working with `application.properties` or `application.yml` files.
The majority of the metadata file is generated automatically at compile time by processing all items annotated with `@ConfigurationProperties`.
However, it is possible to <<configuration-metadata-additional-metadata,write part of the metadata manually>> for corner cases or more advanced use cases.
[[configuration-metadata-format]]
== Metadata Format
Configuration metadata files are located inside jars under `META-INF/spring-configuration-metadata.json`.
They use a simple JSON format with items categorized under either "`groups`" or "`properties`" and additional values hints categorized under "hints", as shown in the following example:
[source,json,indent=0]
----
{"groups": [
{
"name": "server",
"type": "org.springframework.boot.autoconfigure.web.ServerProperties",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "spring.jpa.hibernate",
"type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
"sourceMethod": "getHibernate()"
}
...
],"properties": [
{
"name": "server.port",
"type": "java.lang.Integer",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "server.address",
"type": "java.net.InetAddress",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "spring.jpa.hibernate.ddl-auto",
"type": "java.lang.String",
"description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
}
...
],"hints": [
{
"name": "spring.jpa.hibernate.ddl-auto",
"values": [
{
"value": "none",
"description": "Disable DDL handling."
},
{
"value": "validate",
"description": "Validate the schema, make no changes to the database."
},
{
"value": "update",
"description": "Update the schema if necessary."
},
{
"value": "create",
"description": "Create the schema and destroy previous data."
},
{
"value": "create-drop",
"description": "Create and then destroy the schema at the end of the session."
}
]
}
]}
----
Each "`property`" is a configuration item that the user specifies with a given value.
For example, `server.port` and `server.address` might be specified in `application.properties`, as follows:
[source,properties,indent=0,configprops]
----
server.port=9090
server.address=127.0.0.1
----
The "`groups`" are higher level items that do not themselves specify a value but instead provide a contextual grouping for properties.
For example, the `server.port` and `server.address` properties are part of the `server` group.
NOTE: It is not required that every "`property`" has a "`group`".
Some properties might exist in their own right.
Finally, "`hints`" are additional information used to assist the user in configuring a given property.
For example, when a developer is configuring the configprop:spring.jpa.hibernate.ddl-auto[] property, a tool can use the hints to offer some auto-completion help for the `none`, `validate`, `update`, `create`, and `create-drop` values.
[[configuration-metadata-group-attributes]]
=== Group Attributes
The JSON object contained in the `groups` array can contain the attributes shown in the following table:
[cols="1,1,4"]
|===
| Name | Type | Purpose
| `name`
| String
| The full name of the group.
This attribute is mandatory.
| `type`
| String
| The class name of the data type of the group.
For example, if the group were based on a class annotated with `@ConfigurationProperties`, the attribute would contain the fully qualified name of that class.
If it were based on a `@Bean` method, it would be the return type of that method.
If the type is not known, the attribute may be omitted.
| `description`
| String
| A short description of the group that can be displayed to users.
If no description is available, it may be omitted.
It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
The last line in the description should end with a period (`.`).
| `sourceType`
| String
| The class name of the source that contributed this group.
For example, if the group were based on a `@Bean` method annotated with `@ConfigurationProperties`, this attribute would contain the fully qualified name of the `@Configuration` class that contains the method.
If the source type is not known, the attribute may be omitted.
| `sourceMethod`
| String
| The full name of the method (include parenthesis and argument types) that contributed this group (for example, the name of a `@ConfigurationProperties` annotated `@Bean` method).
If the source method is not known, it may be omitted.
|===
[[configuration-metadata-property-attributes]]
=== Property Attributes
The JSON object contained in the `properties` array can contain the attributes described in the following table:
[cols="1,1,4"]
|===
| Name | Type | Purpose
| `name`
| String
| The full name of the property.
Names are in lower-case period-separated form (for example, `server.address`).
This attribute is mandatory.
| `type`
| String
| The full signature of the data type of the property (for example, `java.lang.String`) but also a full generic type (such as `java.util.Map<java.util.String,acme.MyEnum>`).
You can use this attribute to guide the user as to the types of values that they can enter.
For consistency, the type of a primitive is specified by using its wrapper counterpart (for example, `boolean` becomes `java.lang.Boolean`).
Note that this class may be a complex type that gets converted from a `String` as values are bound.
If the type is not known, it may be omitted.
| `description`
| String
| A short description of the property that can be displayed to users.
If no description is available, it may be omitted.
It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
The last line in the description should end with a period (`.`).
| `sourceType`
| String
| The class name of the source that contributed this property.
For example, if the property were from a class annotated with `@ConfigurationProperties`, this attribute would contain the fully qualified name of that class.
If the source type is unknown, it may be omitted.
| `defaultValue`
| Object
| The default value, which is used if the property is not specified.
If the type of the property is an array, it can be an array of value(s).
If the default value is unknown, it may be omitted.
| `deprecation`
| Deprecation
| Specify whether the property is deprecated.
If the field is not deprecated or if that information is not known, it may be omitted.
The next table offers more detail about the `deprecation` attribute.
|===
The JSON object contained in the `deprecation` attribute of each `properties` element can contain the following attributes:
[cols="1,1,4"]
|===
| Name | Type | Purpose
| `level`
| String
| The level of deprecation, which can be either `warning` (the default) or `error`.
When a property has a `warning` deprecation level, it should still be bound in the environment.
However, when it has an `error` deprecation level, the property is no longer managed and is not bound.
| `reason`
| String
| A short description of the reason why the property was deprecated.
If no reason is available, it may be omitted.
It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
The last line in the description should end with a period (`.`).
| `replacement`
| String
| The full name of the property that _replaces_ this deprecated property.
If there is no replacement for this property, it may be omitted.
|===
NOTE: Prior to Spring Boot 1.3, a single `deprecated` boolean attribute can be used instead of the `deprecation` element.
This is still supported in a deprecated fashion and should no longer be used.
If no reason and replacement are available, an empty `deprecation` object should be set.
Deprecation can also be specified declaratively in code by adding the `@DeprecatedConfigurationProperty` annotation to the getter exposing the deprecated property.
For instance, assume that the `app.acme.target` property was confusing and was renamed to `app.acme.name`.
The following example shows how to handle that situation:
[source,java,indent=0]
----
@ConfigurationProperties("app.acme")
public class AcmeProperties {
private String name;
public String getName() { ... }
public void setName(String name) { ... }
@DeprecatedConfigurationProperty(replacement = "app.acme.name")
@Deprecated
public String getTarget() {
return getName();
}
@Deprecated
public void setTarget(String target) {
setName(target);
}
}
----
NOTE: There is no way to set a `level`.
`warning` is always assumed, since code is still handling the property.
The preceding code makes sure that the deprecated property still works (delegating to the `name` property behind the scenes).
Once the `getTarget` and `setTarget` methods can be removed from your public API, the automatic deprecation hint in the metadata goes away as well.
If you want to keep a hint, adding manual metadata with an `error` deprecation level ensures that users are still informed about that property.
Doing so is particularly useful when a `replacement` is provided.
[[configuration-metadata-hints-attributes]]
=== Hint Attributes
The JSON object contained in the `hints` array can contain the attributes shown in the following table:
[cols="1,1,4"]
|===
| Name | Type | Purpose
| `name`
| String
| The full name of the property to which this hint refers.
Names are in lower-case period-separated form (such as `spring.mvc.servlet.path`).
If the property refers to a map (such as `system.contexts`), the hint either applies to the _keys_ of the map (`system.contexts.keys`) or the _values_ (`system.contexts.values`) of the map.
This attribute is mandatory.
| `values`
| ValueHint[]
| A list of valid values as defined by the `ValueHint` object (described in the next table).
Each entry defines the value and may have a description.
| `providers`
| ValueProvider[]
| A list of providers as defined by the `ValueProvider` object (described later in this document).
Each entry defines the name of the provider and its parameters, if any.
|===
The JSON object contained in the `values` attribute of each `hint` element can contain the attributes described in the following table:
[cols="1,1,4"]
|===
| Name | Type | Purpose
| `value`
| Object
| A valid value for the element to which the hint refers.
If the type of the property is an array, it can also be an array of value(s).
This attribute is mandatory.
| `description`
| String
| A short description of the value that can be displayed to users.
If no description is available, it may be omitted.
It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
The last line in the description should end with a period (`.`).
|===
The JSON object contained in the `providers` attribute of each `hint` element can contain the attributes described in the following table:
[cols="1,1,4"]
|===
|Name | Type |Purpose
| `name`
| String
| The name of the provider to use to offer additional content assistance for the element to which the hint refers.
| `parameters`
| JSON object
| Any additional parameter that the provider supports (check the documentation of the provider for more details).
|===
[[configuration-metadata-repeated-items]]
=== Repeated Metadata Items
Objects with the same "`property`" and "`group`" name can appear multiple times within a metadata file.
For example, you could bind two separate classes to the same prefix, with each having potentially overlapping property names.
While the same names appearing in the metadata multiple times should not be common, consumers of metadata should take care to ensure that they support it.
[[configuration-metadata-providing-manual-hints]]
== Providing Manual Hints
To improve the user experience and further assist the user in configuring a given property, you can provide additional metadata that:
* Describes the list of potential values for a property.
* Associates a provider, to attach a well defined semantic to a property, so that a tool can discover the list of potential values based on the project's context.
=== Value Hint
The `name` attribute of each hint refers to the `name` of a property.
In the <<configuration-metadata-format,initial example shown earlier>>, we provide five values for the `spring.jpa.hibernate.ddl-auto` property: `none`, `validate`, `update`, `create`, and `create-drop`.
Each value may have a description as well.
If your property is of type `Map`, you can provide hints for both the keys and the values (but not for the map itself).
The special `.keys` and `.values` suffixes must refer to the keys and the values, respectively.
Assume a `sample.contexts` maps magic `String` values to an integer, as shown in the following example:
[source,java,indent=0]
----
@ConfigurationProperties("sample")
public class SampleProperties {
private Map<String,Integer> contexts;
// getters and setters
}
----
The magic values are (in this example) are `sample1` and `sample2`.
In order to offer additional content assistance for the keys, you could add the following JSON to <<configuration-metadata-additional-metadata,the manual metadata of the module>>:
[source,json,indent=0]
----
{"hints": [
{
"name": "sample.contexts.keys",
"values": [
{
"value": "sample1"
},
{
"value": "sample2"
}
]
}
]}
----
TIP: We recommend that you use an `Enum` for those two values instead.
If your IDE supports it, this is by far the most effective approach to auto-completion.
=== Value Providers
Providers are a powerful way to attach semantics to a property.
In this section, we define the official providers that you can use for your own hints.
However, your favorite IDE may implement some of these or none of them.
Also, it could eventually provide its own.
NOTE: As this is a new feature, IDE vendors must catch up with how it works.
Adoption times naturally vary.
The following table summarizes the list of supported providers:
[cols="2,4"]
|===
| Name | Description
| `any`
| Permits any additional value to be provided.
| `class-reference`
| Auto-completes the classes available in the project.
Usually constrained by a base class that is specified by the `target` parameter.
| `handle-as`
| Handles the property as if it were defined by the type defined by the mandatory `target` parameter.
| `logger-name`
| Auto-completes valid logger names and <<spring-boot-features.adoc#boot-features-custom-log-groups,logger groups>>.
Typically, package and class names available in the current project can be auto-completed as well as defined groups.
| `spring-bean-reference`
| Auto-completes the available bean names in the current project.
Usually constrained by a base class that is specified by the `target` parameter.
| `spring-profile-name`
| Auto-completes the available Spring profile names in the project.
|===
TIP: Only one provider can be active for a given property, but you can specify several providers if they can all manage the property _in some way_.
Make sure to place the most powerful provider first, as the IDE must use the first one in the JSON section that it can handle.
If no provider for a given property is supported, no special content assistance is provided, either.
==== Any
The special **any** provider value permits any additional values to be provided.
Regular value validation based on the property type should be applied if this is supported.
This provider is typically used if you have a list of values and any extra values should still be considered as valid.
The following example offers `on` and `off` as auto-completion values for `system.state`:
[source,json,indent=0]
----
{"hints": [
{
"name": "system.state",
"values": [
{
"value": "on"
},
{
"value": "off"
}
],
"providers": [
{
"name": "any"
}
]
}
]}
----
Note that, in the preceding example, any other value is also allowed.
==== Class Reference
The **class-reference** provider auto-completes classes available in the project.
This provider supports the following parameters:
[cols="1,1,2,4"]
|===
| Parameter | Type | Default value | Description
| `target`
| `String` (`Class`)
| _none_
| The fully qualified name of the class that should be assignable to the chosen value.
Typically used to filter out-non candidate classes.
Note that this information can be provided by the type itself by exposing a class with the appropriate upper bound.
| `concrete`
| `boolean`
| true
| Specify whether only concrete classes are to be considered as valid candidates.
|===
The following metadata snippet corresponds to the standard `server.servlet.jsp.class-name` property that defines the `JspServlet` class name to use:
[source,json,indent=0]
----
{"hints": [
{
"name": "server.servlet.jsp.class-name",
"providers": [
{
"name": "class-reference",
"parameters": {
"target": "javax.servlet.http.HttpServlet"
}
}
]
}
]}
----
==== Handle As
The **handle-as** provider lets you substitute the type of the property to a more high-level type.
This typically happens when the property has a `java.lang.String` type, because you do not want your configuration classes to rely on classes that may not be on the classpath.
This provider supports the following parameters:
[cols="1,1,2,4"]
|===
| Parameter | Type | Default value | Description
| **`target`**
| `String` (`Class`)
| _none_
| The fully qualified name of the type to consider for the property.
This parameter is mandatory.
|===
The following types can be used:
* Any `java.lang.Enum`: Lists the possible values for the property.
(We recommend defining the property with the `Enum` type, as no further hint should be required for the IDE to auto-complete the values)
* `java.nio.charset.Charset`: Supports auto-completion of charset/encoding values (such as `UTF-8`)
* `java.util.Locale`: auto-completion of locales (such as `en_US`)
* `org.springframework.util.MimeType`: Supports auto-completion of content type values (such as `text/plain`)
* `org.springframework.core.io.Resource`: Supports auto-completion of Springs Resource abstraction to refer to a file on the filesystem or on the classpath (such as `classpath:/sample.properties`)
TIP: If multiple values can be provided, use a `Collection` or _Array_ type to teach the IDE about it.
The following metadata snippet corresponds to the standard `spring.liquibase.change-log` property that defines the path to the changelog to use.
It is actually used internally as a `org.springframework.core.io.Resource` but cannot be exposed as such, because we need to keep the original String value to pass it to the Liquibase API.
[source,json,indent=0]
----
{"hints": [
{
"name": "spring.liquibase.change-log",
"providers": [
{
"name": "handle-as",
"parameters": {
"target": "org.springframework.core.io.Resource"
}
}
]
}
]}
----
==== Logger Name
The **logger-name** provider auto-completes valid logger names and <<spring-boot-features.adoc#boot-features-custom-log-groups,logger groups>>.
Typically, package and class names available in the current project can be auto-completed.
If groups are enabled (default) and if a custom logger group is identified in the configuration, auto-completion for it should be provided.
Specific frameworks may have extra magic logger names that can be supported as well.
This provider supports the following parameters:
[cols="1,1,2,4"]
|===
| Parameter | Type | Default value | Description
| `group`
| `boolean`
| `true`
| Specify whether known groups should be considered.
|===
Since a logger name can be any arbitrary name, this provider should allow any value but could highlight valid package and class names that are not available in the project's classpath.
The following metadata snippet corresponds to the standard `logging.level` property.
Keys are _logger names_, and values correspond to the standard log levels or any custom level.
As Spring Boot defines a few logger groups out-of-the-box, dedicated value hints have been added for those.
[source,json,indent=0]
----
{"hints": [
{
"name": "logging.level.keys",
"values": [
{
"value": "root",
"description": "Root logger used to assign the default logging level."
},
{
"value": "sql",
"description": "SQL logging group including Hibernate SQL logger."
},
{
"value": "web",
"description": "Web logging group including codecs."
}
],
"providers": [
{
"name": "logger-name"
}
]
},
{
"name": "logging.level.values",
"values": [
{
"value": "trace"
},
{
"value": "debug"
},
{
"value": "info"
},
{
"value": "warn"
},
{
"value": "error"
},
{
"value": "fatal"
},
{
"value": "off"
}
],
"providers": [
{
"name": "any"
}
]
}
]}
----
==== Spring Bean Reference
The **spring-bean-reference** provider auto-completes the beans that are defined in the configuration of the current project.
This provider supports the following parameters:
[cols="1,1,2,4"]
|===
| Parameter | Type | Default value | Description
| `target`
| `String` (`Class`)
| _none_
| The fully qualified name of the bean class that should be assignable to the candidate.
Typically used to filter out non-candidate beans.
|===
The following metadata snippet corresponds to the standard `spring.jmx.server` property that defines the name of the `MBeanServer` bean to use:
[source,json,indent=0]
----
{"hints": [
{
"name": "spring.jmx.server",
"providers": [
{
"name": "spring-bean-reference",
"parameters": {
"target": "javax.management.MBeanServer"
}
}
]
}
]}
----
NOTE: The binder is not aware of the metadata.
If you provide that hint, you still need to transform the bean name into an actual Bean reference using by the `ApplicationContext`.
==== Spring Profile Name
The **spring-profile-name** provider auto-completes the Spring profiles that are defined in the configuration of the current project.
The following metadata snippet corresponds to the standard `spring.profiles.active` property that defines the name of the Spring profile(s) to enable:
[source,json,indent=0]
----
{"hints": [
{
"name": "spring.profiles.active",
"providers": [
{
"name": "spring-profile-name"
}
]
}
]}
----
[[configuration-metadata-annotation-processor]]
== Generating Your Own Metadata by Using the Annotation Processor
You can easily generate your own configuration metadata file from items annotated with `@ConfigurationProperties` by using the `spring-boot-configuration-processor` jar.
The jar includes a Java annotation processor which is invoked as your project is compiled.
To use the processor, include a dependency on `spring-boot-configuration-processor`.
With Maven the dependency should be declared as optional, as shown in the following example:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
----
With Gradle 4.5 and earlier, the dependency should be declared in the `compileOnly` configuration, as shown in the following example:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
----
dependencies {
compileOnly "org.springframework.boot:spring-boot-configuration-processor"
}
----
With Gradle 4.6 and later, the dependency should be declared in the `annotationProcessor` configuration, as shown in the following example:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
----
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
}
----
If you are using an `additional-spring-configuration-metadata.json` file, the `compileJava` task should be configured to depend on the `processResources` task, as shown in the following example:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
----
compileJava.dependsOn(processResources)
----
This dependency ensures that the additional metadata is available when the annotation processor runs during compilation.
The processor picks up both classes and methods that are annotated with `@ConfigurationProperties`.
The Javadoc for field values within configuration classes is used to populate the `description` attribute.
NOTE: You should only use simple text with `@ConfigurationProperties` field Javadoc, since they are not processed before being added to the JSON.
If the class has a single constructor with at least one parameters, one property is created per constructor parameter.
Otherwise, properties are discovered through the presence of standard getters and setters with special handling for collection types (that is detected even if only a getter is present).
The annotation processor also supports the use of the `@Data`, `@Getter`, and `@Setter` lombok annotations.
The annotation processor cannot auto-detect default values for ``Enum``s and ``Collections``s.
In the cases where a `Collection` or `Enum` property has a non-empty default value, <<configuration-metadata-additional-metadata,manual metadata>> should be provided.
Consider the following class:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@ConfigurationProperties(prefix = "acme.messaging")
public class MessagingProperties {
private List<String> addresses = new ArrayList<>(Arrays.asList("a", "b"));
private ContainerType containerType = ContainerType.SIMPLE;
// ... getter and setters
public enum ContainerType {
SIMPLE,
DIRECT
}
}
----
In order to document default values for properties in the class above, you could add the following content to <<configuration-metadata-additional-metadata,the manual metadata of the module>>:
[source,json,indent=0]
----
{"properties": [
{
"name": "acme.messaging.addresses",
"defaultValue": ["a", "b"]
},
{
"name": "acme.messaging.container-type",
"defaultValue": "simple"
}
]}
----
Only the `name` of the property is required to document additional fields with manual metadata.
[NOTE]
====
If you are using AspectJ in your project, you need to make sure that the annotation processor runs only once.
There are several ways to do this.
With Maven, you can configure the `maven-apt-plugin` explicitly and add the dependency to the annotation processor only there.
You could also let the AspectJ plugin run all the processing and disable annotation processing in the `maven-compiler-plugin` configuration, as follows:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<proc>none</proc>
</configuration>
</plugin>
----
====
[[configuration-metadata-nested-properties]]
=== Nested Properties
The annotation processor automatically considers inner classes as nested properties.
Consider the following class:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@ConfigurationProperties(prefix="server")
public class ServerProperties {
private String name;
private Host host;
// ... getter and setters
public static class Host {
private String ip;
private int port;
// ... getter and setters
}
}
----
The preceding example produces metadata information for `server.name`, `server.host.ip`, and `server.host.port` properties.
You can use the `@NestedConfigurationProperty` annotation on a field to indicate that a regular (non-inner) class should be treated as if it were nested.
TIP: This has no effect on collections and maps, as those types are automatically identified, and a single metadata property is generated for each of them.
[[configuration-metadata-additional-metadata]]
=== Adding Additional Metadata
Spring Boot's configuration file handling is quite flexible, and it is often the case that properties may exist that are not bound to a `@ConfigurationProperties` bean.
You may also need to tune some attributes of an existing key.
To support such cases and let you provide custom "hints", the annotation processor automatically merges items from `META-INF/additional-spring-configuration-metadata.json` into the main metadata file.
If you refer to a property that has been detected automatically, the description, default value, and deprecation information are overridden, if specified.
If the manual property declaration is not identified in the current module, it is added as a new property.
The format of the `additional-spring-configuration-metadata.json` file is exactly the same as the regular `spring-configuration-metadata.json`.
The additional properties file is optional.
If you do not have any additional properties, do not add the file.

View File

@@ -0,0 +1,14 @@
[appendix]
[[dependency-versions]]
= Dependency versions
include::attributes.adoc[]
This appendix provides details of the dependencies that are managed by Spring Boot.
[[dependency-versions-coordinates]]
== Managed Dependency Coordinates
The following table provides details of all of the dependency versions that are provided by Spring Boot in its CLI (Command Line Interface), Maven dependency management, and Gradle plugin.
When you declare a dependency on one of these artifacts without declaring a version, the version listed in the table is used.
include::dependency-versions.adoc[]

View File

@@ -0,0 +1,281 @@
[appendix]
[[executable-jar]]
= The Executable Jar Format
include::attributes.adoc[]
The `spring-boot-loader` modules lets Spring Boot support executable jar and war files.
If you use the Maven plugin or the Gradle plugin, executable jars are automatically generated, and you generally do not need to know the details of how they work.
If you need to create executable jars from a different build system or if you are just curious about the underlying technology, this appendix provides some background.
[[executable-jar-nested-jars]]
== Nested JARs
Java does not provide any standard way to load nested jar files (that is, jar files that are themselves contained within a jar).
This can be problematic if you need to distribute a self-contained application that can be run from the command line without unpacking.
To solve this problem, many developers use "`shaded`" jars.
A shaded jar packages all classes, from all jars, into a single "`uber jar`".
The problem with shaded jars is that it becomes hard to see which libraries are actually in your application.
It can also be problematic if the same filename is used (but with different content) in multiple jars.
Spring Boot takes a different approach and lets you actually nest jars directly.
[[executable-jar-jar-file-structure]]
=== The Executable Jar File Structure
Spring Boot Loader-compatible jar files should be structured in the following way:
[indent=0]
----
example.jar
|
+-META-INF
| +-MANIFEST.MF
+-org
| +-springframework
| +-boot
| +-loader
| +-<spring boot loader classes>
+-BOOT-INF
+-classes
| +-mycompany
| +-project
| +-YourClasses.class
+-lib
+-dependency1.jar
+-dependency2.jar
----
Application classes should be placed in a nested `BOOT-INF/classes` directory.
Dependencies should be placed in a nested `BOOT-INF/lib` directory.
[[executable-jar-war-file-structure]]
=== The Executable War File Structure
Spring Boot Loader-compatible war files should be structured in the following way:
[indent=0]
----
example.war
|
+-META-INF
| +-MANIFEST.MF
+-org
| +-springframework
| +-boot
| +-loader
| +-<spring boot loader classes>
+-WEB-INF
+-classes
| +-com
| +-mycompany
| +-project
| +-YourClasses.class
+-lib
| +-dependency1.jar
| +-dependency2.jar
+-lib-provided
+-servlet-api.jar
+-dependency3.jar
----
Dependencies should be placed in a nested `WEB-INF/lib` directory.
Any dependencies that are required when running embedded but are not required when deploying to a traditional web container should be placed in `WEB-INF/lib-provided`.
[[executable-jar-jarfile]]
== Spring Boot's "`JarFile`" Class
The core class used to support loading nested jars is `org.springframework.boot.loader.jar.JarFile`.
It lets you load jar content from a standard jar file or from nested child jar data.
When first loaded, the location of each `JarEntry` is mapped to a physical file offset of the outer jar, as shown in the following example:
[indent=0]
----
myapp.jar
+-------------------+-------------------------+
| /BOOT-INF/classes | /BOOT-INF/lib/mylib.jar |
|+-----------------+||+-----------+----------+|
|| A.class ||| B.class | C.class ||
|+-----------------+||+-----------+----------+|
+-------------------+-------------------------+
^ ^ ^
0063 3452 3980
----
The preceding example shows how `A.class` can be found in `/BOOT-INF/classes` in `myapp.jar` at position `0063`.
`B.class` from the nested jar can actually be found in `myapp.jar` at position `3452`, and `C.class` is at position `3980`.
Armed with this information, we can load specific nested entries by seeking to the appropriate part of the outer jar.
We do not need to unpack the archive, and we do not need to read all entry data into memory.
[[executable-jar-jarfile-compatibility]]
=== Compatibility with the Standard Java "`JarFile`"
Spring Boot Loader strives to remain compatible with existing code and libraries.
`org.springframework.boot.loader.jar.JarFile` extends from `java.util.jar.JarFile` and should work as a drop-in replacement.
The `getURL()` method returns a `URL` that opens a connection compatible with `java.net.JarURLConnection` and can be used with Java's `URLClassLoader`.
[[executable-jar-launching]]
== Launching Executable Jars
The `org.springframework.boot.loader.Launcher` class is a special bootstrap class that is used as an executable jar's main entry point.
It is the actual `Main-Class` in your jar file, and it is used to setup an appropriate `URLClassLoader` and ultimately call your `main()` method.
There are three launcher subclasses (`JarLauncher`, `WarLauncher`, and `PropertiesLauncher`).
Their purpose is to load resources (`.class` files and so on) from nested jar files or war files in directories (as opposed to those explicitly on the classpath).
In the case of `JarLauncher` and `WarLauncher`, the nested paths are fixed.
`JarLauncher` looks in `BOOT-INF/lib/`, and `WarLauncher` looks in `WEB-INF/lib/` and `WEB-INF/lib-provided/`.
You can add extra jars in those locations if you want more.
The `PropertiesLauncher` looks in `BOOT-INF/lib/` in your application archive by default.
You can add additional locations by setting an environment variable called `LOADER_PATH` or `loader.path` in `loader.properties` (which is a comma-separated list of directories, archives, or directories within archives).
[[executable-jar-launcher-manifest]]
=== Launcher Manifest
You need to specify an appropriate `Launcher` as the `Main-Class` attribute of `META-INF/MANIFEST.MF`.
The actual class that you want to launch (that is, the class that contains a `main` method) should be specified in the `Start-Class` attribute.
The following example shows a typical `MANIFEST.MF` for an executable jar file:
[indent=0]
----
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.mycompany.project.MyApplication
----
For a war file, it would be as follows:
[indent=0]
----
Main-Class: org.springframework.boot.loader.WarLauncher
Start-Class: com.mycompany.project.MyApplication
----
NOTE: You need not specify `Class-Path` entries in your manifest file.
The classpath is deduced from the nested jars.
[[executable-jar-property-launcher-features]]
== `PropertiesLauncher` Features
`PropertiesLauncher` has a few special features that can be enabled with external properties (System properties, environment variables, manifest entries, or `loader.properties`).
The following table describes these properties:
|===
| Key | Purpose
| `loader.path`
| Comma-separated Classpath, such as `lib,$\{HOME}/app/lib`.
Earlier entries take precedence, like a regular `-classpath` on the `javac` command line.
| `loader.home`
| Used to resolve relative paths in `loader.path`.
For example, given `loader.path=lib`, then `${loader.home}/lib` is a classpath location (along with all jar files in that directory).
This property is also used to locate a `loader.properties` file, as in the following example `file:///opt/app` It defaults to `${user.dir}`.
| `loader.args`
| Default arguments for the main method (space separated).
| `loader.main`
| Name of main class to launch (for example, `com.app.Application`).
| `loader.config.name`
| Name of properties file (for example, `launcher`).
It defaults to `loader`.
| `loader.config.location`
| Path to properties file (for example, `classpath:loader.properties`).
It defaults to `loader.properties`.
| `loader.system`
| Boolean flag to indicate that all properties should be added to System properties.
It defaults to `false`.
|===
When specified as environment variables or manifest entries, the following names should be used:
|===
| Key | Manifest entry | Environment variable
| `loader.path`
| `Loader-Path`
| `LOADER_PATH`
| `loader.home`
| `Loader-Home`
| `LOADER_HOME`
| `loader.args`
| `Loader-Args`
| `LOADER_ARGS`
| `loader.main`
| `Start-Class`
| `LOADER_MAIN`
| `loader.config.location`
| `Loader-Config-Location`
| `LOADER_CONFIG_LOCATION`
| `loader.system`
| `Loader-System`
| `LOADER_SYSTEM`
|===
TIP: Build plugins automatically move the `Main-Class` attribute to `Start-Class` when the fat jar is built.
If you use that, specify the name of the class to launch by using the `Main-Class` attribute and leaving out `Start-Class`.
The following rules apply to working with `PropertiesLauncher`:
* `loader.properties` is searched for in `loader.home`, then in the root of the classpath, and then in `classpath:/BOOT-INF/classes`.
The first location where a file with that name exists is used.
* `loader.home` is the directory location of an additional properties file (overriding the default) only when `loader.config.location` is not specified.
* `loader.path` can contain directories (which are scanned recursively for jar and zip files), archive paths, a directory within an archive that is scanned for jar files (for example, `dependencies.jar!/lib`), or wildcard patterns (for the default JVM behavior).
Archive paths can be relative to `loader.home` or anywhere in the file system with a `jar:file:` prefix.
* `loader.path` (if empty) defaults to `BOOT-INF/lib` (meaning a local directory or a nested one if running from an archive).
Because of this, `PropertiesLauncher` behaves the same as `JarLauncher` when no additional configuration is provided.
* `loader.path` can not be used to configure the location of `loader.properties` (the classpath used to search for the latter is the JVM classpath when `PropertiesLauncher` is launched).
* Placeholder replacement is done from System and environment variables plus the properties file itself on all values before use.
* The search order for properties (where it makes sense to look in more than one place) is environment variables, system properties, `loader.properties`, the exploded archive manifest, and the archive manifest.
[[executable-jar-restrictions]]
== Executable Jar Restrictions
You need to consider the following restrictions when working with a Spring Boot Loader packaged application:
[[executable-jar-zip-entry-compression]]
* Zip entry compression:
The `ZipEntry` for a nested jar must be saved by using the `ZipEntry.STORED` method.
This is required so that we can seek directly to individual content within the nested jar.
The content of the nested jar file itself can still be compressed, as can any other entries in the outer jar.
[[executable-jar-system-classloader]]
* System classLoader:
Launched applications should use `Thread.getContextClassLoader()` when loading classes (most libraries and frameworks do so by default).
Trying to load nested jar classes with `ClassLoader.getSystemClassLoader()` fails.
`java.util.Logging` always uses the system classloader.
For this reason, you should consider a different logging implementation.
[[executable-jar-alternatives]]
== Alternative Single Jar Solutions
If the preceding restrictions mean that you cannot use Spring Boot Loader, consider the following alternatives:
* https://maven.apache.org/plugins/maven-shade-plugin/[Maven Shade Plugin]
* http://www.jdotsoft.com/JarClassLoader.php[JarClassLoader]
* https://sourceforge.net/projects/one-jar/[OneJar]
* https://imperceptiblethoughts.com/shadow/[Gradle Shadow Plugin]

View File

@@ -0,0 +1,13 @@
[appendix]
[[test-auto-configuration]]
= Test Auto-configuration Annotations
include::attributes.adoc[]
This appendix describes the `@…Test` auto-configuration annotations that Spring Boot provides to test slices of your application.
[[test-auto-configuration-slices]]
== Test Slices
The following table lists the various `@…Test` annotations that can be used to test slices of your application and the auto-configuration that they import by default:
include::test-slice-auto-configuration.adoc[]

View File

@@ -0,0 +1,108 @@
:doctype: book
:idprefix:
:idseparator: -
:toc: left
:toclevels: 4
:tabsize: 4
:numbered:
:sectanchors:
:sectnums:
:icons: font
:hide-uri-scheme:
:docinfo: shared,private
:spring-boot-artifactory-repo: snapshot
:github-tag: master
:spring-boot-version: current
:github-repo: spring-projects/spring-boot
:github-raw: https://raw.githubusercontent.com/{github-repo}/{github-tag}
:github-issues: https://github.com/{github-repo}/issues/
:github-wiki: https://github.com/{github-repo}/wiki
:code-examples: ../main/java/org/springframework/boot/docs
:test-examples: ../test/java/org/springframework/boot/docs
:spring-boot-code: https://github.com/{github-repo}/tree/{github-tag}
:spring-boot-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/api/
:spring-boot-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference
:spring-boot-master-code: https://github.com/{github-repo}/tree/master
:spring-boot-current-docs: https://docs.spring.io/spring-boot/docs/current/reference
:spring-boot-actuator-restapi: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/actuator-api/
:spring-boot-maven-plugin-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/maven-plugin/html/
:spring-boot-gradle-plugin-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/gradle-plugin/reference/html/
:spring-boot-gradle-plugin-pdfdocs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/gradle-plugin/reference/pdf/spring-boot-gradle-plugin-reference.pdf
:spring-boot-gradle-plugin-api: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/gradle-plugin/reference/api/
:spring-boot-module-code: {spring-boot-code}/spring-boot-project/spring-boot/src/main/java/org/springframework/boot
:spring-boot-module-api: {spring-boot-api}/org/springframework/boot
:spring-boot-autoconfigure-module-code: {spring-boot-code}/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure
:spring-boot-autoconfigure-module-api: {spring-boot-api}/org/springframework/boot/autoconfigure
:spring-boot-actuator-module-code: {spring-boot-code}/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate
:spring-boot-actuator-module-api: {spring-boot-api}/org/springframework/boot/actuate
:spring-boot-actuator-autoconfigure-module-code: {spring-boot-code}/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure
:spring-boot-actuator-autoconfigure-module-api: : {spring-boot-api}/org/springframework/boot/actuate/autoconfigure
:spring-boot-cli-module-code: {spring-boot-code}/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli
:spring-boot-cli-module-api: {spring-boot-api}/org/springframework/boot/cli
:spring-boot-devtools-module-code: {spring-boot-code}/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools
:spring-boot-devtools-module-api: {spring-boot-api}/org/springframework/boot/devtools
:spring-boot-test-module-code: {spring-boot-code}/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test
:spring-boot-test-module-api: {spring-boot-api}/org/springframework/boot/test
:spring-boot-test-autoconfigure-module-code: {spring-boot-code}/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure
:spring-boot-test-autoconfigure-module-api: {spring-boot-api}/org/springframework/boot/test/autoconfigure
:spring-amqp-api: https://docs.spring.io/spring-amqp/docs/{spring-amqp-version}/api/org/springframework/amqp
:spring-batch: https://spring.io/projects/spring-batch
:spring-batch-api: https://docs.spring.io/spring-batch/docs/{spring-batch-version}/api/org/springframework/batch
:spring-batch-docs: https://docs.spring.io/spring-batch/docs/{spring-batch-version}/reference/html/
:spring-data: https://spring.io/projects/spring-data
:spring-data-cassandra: https://spring.io/projects/spring-data-cassandra
:spring-data-commons-api: https://docs.spring.io/spring-data/commons/docs/{spring-data-commons-version}/api/org/springframework/data
:spring-data-couchbase: https://spring.io/projects/spring-data-couchbase
:spring-data-couchbase-docs: https://docs.spring.io/spring-data/couchbase/docs/{spring-data-couchbase-version}/reference/html/
:spring-data-elasticsearch: https://spring.io/projects/spring-data-elasticsearch
:spring-data-elasticsearch-docs: https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/
:spring-data-gemfire: https://spring.io/projects/spring-data-gemfire
:spring-data-geode: https://spring.io/projects/spring-data-geode
:spring-data-jpa: https://spring.io/projects/spring-data-jpa
:spring-data-jpa-api: https://docs.spring.io/spring-data/jpa/docs/{spring-data-jpa-version}/api/org/springframework/data/jpa
:spring-data-jdbc-docs: https://docs.spring.io/spring-data/jdbc/docs/{spring-data-jdbc-version}/reference/html/
:spring-data-ldap: https://spring.io/projects/spring-data-ldap
:spring-data-mongodb: https://spring.io/projects/spring-data-mongodb
:spring-data-mongodb-api: https://docs.spring.io/spring-data/mongodb/docs/{spring-data-mongodb-version}/api/org/springframework/data/mongodb
:spring-data-neo4j: https://spring.io/projects/spring-data-neo4j
:spring-data-neo4j-docs: https://docs.spring.io/spring-data/neo4j/docs/{spring-data-neo4j-version}/reference/html/
:spring-data-redis: https://spring.io/projects/spring-data-redis
:spring-data-rest-api: https://docs.spring.io/spring-data/rest/docs/{spring-data-rest-version}/api/org/springframework/data/rest
:spring-data-solr: https://spring.io/projects/spring-data-solr
:spring-data-solr-docs: https://docs.spring.io/spring-data/solr/docs/{spring-data-solr-version}/reference/html/
:spring-framework: https://spring.io/projects/spring-framework
:spring-framework-api: https://docs.spring.io/spring/docs/{spring-framework-version}/javadoc-api/org/springframework
:spring-framework-docs: https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/
:spring-initializr-docs: https://docs.spring.io/initializr/docs/current/reference/html/
:spring-integration: https://spring.io/projects/spring-integration
:spring-integration-docs: https://docs.spring.io/spring-integration/docs/{spring-integration-version}/reference/html/
:spring-restdocs: https://spring.io/projects/spring-restdocs
:spring-security: https://spring.io/projects/spring-security
:spring-security-docs: https://docs.spring.io/spring-security/site/docs/{spring-security-version}/reference/htmlsingle/
:spring-security-oauth2: https://spring.io/projects/spring-security-oauth
:spring-security-oauth2-docs: https://projects.spring.io/spring-security-oauth/docs/oauth2.html
:spring-session: https://spring.io/projects/spring-session
:spring-webservices-docs: https://docs.spring.io/spring-ws/docs/{spring-webservices-version}/reference/
:ant-docs: https://ant.apache.org/manual
:dependency-management-plugin-code: https://github.com/spring-gradle-plugins/dependency-management-plugin
:gradle-docs: https://docs.gradle.org/current/userguide
:hibernate-docs: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html
:java-api: https://docs.oracle.com/javase/8/docs/api/
:jetty-docs: https://www.eclipse.org/jetty/documentation/{jetty-version}
:jooq-docs: https://www.jooq.org/doc/{jooq-version}/manual-single-page
:junit5-docs: https://junit.org/junit5/docs/current/user-guide
:kotlin-docs: https://kotlinlang.org/docs/reference/
:micrometer-docs: https://micrometer.io/docs
:micrometer-concepts-docs: {micrometer-docs}/concepts
:micrometer-registry-docs: {micrometer-docs}/registry
:tomcat-docs: https://tomcat.apache.org/tomcat-9.0-doc

View File

@@ -0,0 +1,382 @@
[[build-tool-plugins]]
= Build Tool Plugins
include::attributes.adoc[]
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-spring-boot.adoc#using-boot-build-systems>>`" from the "`<<using-spring-boot.adoc#using-boot>>`" section first.
[[build-tool-plugins-maven-plugin]]
== 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).
NOTE: See the {spring-boot-maven-plugin-docs}[Spring Boot Maven Plugin Documentation] for complete plugin documentation.
[[build-tool-plugins-include-maven-plugin]]
=== Including the Plugin
To use the Spring Boot Maven Plugin, include the appropriate XML in the `plugins` section of your `pom.xml`, as shown in the following example:
[source,xml,indent=0,subs="verbatim,attributes"]
----
<?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>
<!-- ... -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>{spring-boot-version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
----
The preceding configuration repackages a jar or war that is built during the `package` phase of the Maven lifecycle.
The following example shows both the repackaged jar as well as the original jar in the `target` directory:
[indent=0]
----
$ mvn package
$ ls target/*.jar
target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original
----
If you do not include the `<execution/>` configuration, as shown in the prior example, you can run the plugin on its own (but only if the package goal is used as well), as shown in the following example:
[indent=0]
----
$ mvn package spring-boot:repackage
$ ls target/*.jar
target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original
----
If you use a milestone or snapshot release, you also need to add the appropriate `pluginRepository` elements, as shown in the following listing:
[source,xml,indent=0,subs="verbatim,attributes"]
----
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
----
[[build-tool-plugins-maven-packaging]]
=== Packaging Executable Jar and War Files
Once `spring-boot-maven-plugin` has been included in your `pom.xml`, it automatically tries to rewrite archives to make them executable by using the `spring-boot:repackage` goal.
You should configure your project to build a jar or war (as appropriate) by using the usual `packaging` element, as shown in the following example:
[source,xml,indent=0,subs="verbatim,attributes"]
----
<?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">
<!-- ... -->
<packaging>jar</packaging>
<!-- ... -->
</project>
----
Your existing archive is enhanced by Spring Boot during the `package` phase.
The main class that you want to launch can be specified either by using a configuration option, as shown below, or by adding a `Main-Class` attribute to the manifest.
If you do not specify a main class, the plugin searches for a class with a `public static void main(String[] args)` method.
[source,xml,indent=0,subs="verbatim,attributes"]
----
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.example.app.Main</mainClass>
</configuration>
</plugin>
----
To build and run a project artifact, you can type the following:
[indent=0]
----
$ mvn package
$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar
----
To build a war file that is both executable and deployable into an external container, you need to mark the embedded container dependencies as "`provided`", as shown in the following example:
[source,xml,indent=0,subs="verbatim,attributes"]
----
<?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">
<!-- ... -->
<packaging>war</packaging>
<!-- ... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- ... -->
</dependencies>
</project>
----
TIP: See the "`<<howto.adoc#howto-create-a-deployable-war-file>>`" section for more details on how to create a deployable war file.
Advanced configuration options and examples are available in the {spring-boot-maven-plugin-docs}[plugin info page].
[[build-tool-plugins-gradle-plugin]]
== 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 5.x (4.10 is also supported but this support is deprecated and will be removed in a future release).
Please refer to the plugin's documentation to learn more:
* Reference ({spring-boot-gradle-plugin-docs}[HTML] and {spring-boot-gradle-plugin-pdfdocs}[PDF])
* {spring-boot-gradle-plugin-api}[API]
[[build-tool-plugins-antlib]]
== 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:
[source,xml,indent=0]
----
<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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ ant -lib <folder containing spring-boot-antlib-{spring-boot-version}.jar>
----
TIP: The "`Using Spring Boot`" section includes a more complete example of <<using-spring-boot.adoc#using-boot-ant, using Apache Ant with `spring-boot-antlib`>>.
[[spring-boot-ant-tasks]]
=== Spring Boot Ant Tasks
Once the `spring-boot-antlib` namespace has been declared, the following additional tasks are available:
* <<spring-boot-ant-exejar>>
* <<spring-boot-ant-findmainclass>>
[[spring-boot-ant-exejar]]
==== `spring-boot:exejar`
You can use the `exejar` task to create a Spring Boot executable jar.
The following attributes are supported by the task:
[cols="1,2,2"]
|====
| 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:
[cols="1,4"]
|====
| Element | Description
| `resources`
| One or more {ant-docs}/Types/resources.html#collection[Resource Collections] describing a set of {ant-docs}/Types/resources.html[Resources] that should be added to the content of the created +jar+ file.
| `lib`
| One or more {ant-docs}/Types/resources.html#collection[Resource Collections] that should be added to the set of jar libraries that make up the runtime dependency classpath of the application.
|====
[[spring-boot-ant-exejar-examples]]
==== Examples
This section shows two examples of Ant tasks.
.Specify +start-class+
[source,xml,indent=0]
----
<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+
[source,xml,indent=0]
----
<exejar destfile="target/my-application.jar" classes="target/classes">
<lib>
<fileset dir="lib" />
</lib>
</exejar>
----
[[spring-boot-ant-findmainclass]]
=== `spring-boot:findmainclass`
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:
[cols="1,2,2"]
|====
| 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)_
|====
[[spring-boot-ant-findmainclass-examples]]
==== Examples
This section contains three examples of using `findmainclass`.
.Find and log
[source,xml,indent=0]
----
<findmainclass classesroot="target/classes" />
----
.Find and set
[source,xml,indent=0]
----
<findmainclass classesroot="target/classes" property="main-class" />
----
.Override and set
[source,xml,indent=0]
----
<findmainclass mainclass="com.example.MainClass" property="main-class" />
----
[[build-tool-plugins-other-build-systems]]
== 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 "`<<appendix-executable-jar-format.adoc#executable-jar, executable jar format>>`" 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-repackaging-archives]]
=== 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-nested-libraries]]
=== 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-find-a-main-class]]
=== Finding a Main Class
If you do not use `Repackager.setMainClass()` to specify a main class, the repackager uses https://asm.ow2.io/[ASM] 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-repackage-implementation]]
=== Example Repackage Implementation
The following example shows a typical repackage implementation:
[source,java,indent=0]
----
Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(false);
repackager.repackage(new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
// Build system specific implementation, callback for each dependency
// callback.library(new Library(nestedFile, LibraryScope.COMPILE));
}
});
----
[[build-tool-plugins-whats-next]]
== What to Read Next
If you are interested in how the build tool plugins work, you can look at the {spring-boot-code}/spring-boot-project/spring-boot-tools[`spring-boot-tools`] module on GitHub.
More technical details of the executable jar format are covered in <<appendix-executable-jar-format#executable-jar,the appendix>>.
If you have specific build-related questions, you can check out the "`<<howto.adoc#howto, how-to>>`" guides.

View File

@@ -0,0 +1,847 @@
[[deployment]]
= Deploying Spring Boot Applications
include::attributes.adoc[]
Spring Boot's flexible packaging options provide a great deal of choice when it comes to deploying your application.
You can deploy Spring Boot applications to a variety of cloud platforms, to container images (such as Docker), or to virtual/real machines.
This section covers some of the more common deployment scenarios.
[[containers-deployment]]
== Deploying to Containers
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.
The simplest way to run an unpacked archive is by starting the appropriate launcher, as follows:
[indent=0]
----
$ 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 shouldn't 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:
[indent=0]
----
$ jar -xf myapp.jar
$ java -cp BOOT-INF/classes:BOOT-INF/lib/* com.example.MyApplication
----
More efficient container images can also be created by copying the dependencies to the image as a separate layer from the application classes and resources (which normally change more frequently).
There is more than one way to achieve this layer separation.
For example, using a `Dockerfile` you could express it in this form:
[indent=0]
----
FROM openjdk:8-jdk-alpine AS builder
WORKDIR target/dependency
ARG APPJAR=target/*.jar
COPY ${APPJAR} app.jar
RUN jar -xf ./app.jar
FROM openjdk:8-jre-alpine
VOLUME /tmp
ARG DEPENDENCY=target/dependency
COPY --from=builder ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=builder ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=builder ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","com.example.MyApplication"]
----
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:
[indent=0]
----
docker build --build-arg APPJAR=path/to/myapp.jar .
----
[[cloud-deployment]]
== Deploying to the Cloud
Spring Boot's executable jars are ready-made for most popular cloud PaaS (Platform-as-a-Service) providers.
These providers tend to require that you "`bring your own container`".
They manage application processes (not Java applications specifically), so they need an intermediary layer that adapts _your_ application to the _cloud's_ notion of a running process.
Two popular cloud providers, Heroku and Cloud Foundry, employ a "`buildpack`" approach.
The buildpack wraps your deployed code in whatever is needed to _start_ your application.
It might be a JDK and a call to `java`, an embedded web server, or a full-fledged application server.
A buildpack is pluggable, but ideally you should be able to get by with as few customizations to it as possible.
This reduces the footprint of functionality that is not under your control.
It minimizes divergence between development and production environments.
Ideally, your application, like a Spring Boot executable jar, has everything that it needs to run packaged within it.
In this section, we look at what it takes to get the <<getting-started.adoc#getting-started-first-application, simple application that we developed>> in the "`Getting Started`" section up and running in the Cloud.
[[cloud-deployment-cloud-foundry]]
=== Cloud Foundry
Cloud Foundry provides default buildpacks that come into play if no other buildpack is specified.
The Cloud Foundry https://github.com/cloudfoundry/java-buildpack[Java buildpack] has excellent support for Spring applications, including Spring Boot.
You can deploy stand-alone executable jar applications as well as traditional `.war` packaged applications.
Once you have built your application (by using, for example, `mvn clean package`) and have https://docs.cloudfoundry.org/cf-cli/install-go-cli.html[installed the `cf` command line tool], deploy your application by using the `cf push` command, substituting the path to your compiled `.jar`.
Be sure to have https://docs.cloudfoundry.org/cf-cli/getting-started.html#login[logged in with your `cf` command line client] before pushing an application.
The following line shows using the `cf push` command to deploy an application:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar
----
NOTE: In the preceding example, we substitute `acloudyspringtime` for whatever value you give `cf` as the name of your application.
See the https://docs.cloudfoundry.org/cf-cli/getting-started.html#push[`cf push` documentation] for more options.
If there is a Cloud Foundry https://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html[`manifest.yml`] file present in the same directory, it is considered.
At this point, `cf` starts uploading your application, producing output similar to the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
Uploading acloudyspringtime... *OK*
Preparing to start acloudyspringtime... *OK*
-----> Downloaded app package (*8.9M*)
-----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e
-----> Downloading Open Jdk JRE 1.8.0_121 from https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz (found in cache)
Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s)
-----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache)
Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K
-----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache)
Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s)
-----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache)
Checking status of app 'acloudyspringtime'...
0 of 1 instances running (1 starting)
...
0 of 1 instances running (1 starting)
...
0 of 1 instances running (1 starting)
...
1 of 1 instances running (1 running)
App started
----
Congratulations! The application is now live!
Once your application is live, you can verify the status of the deployed application by using the `cf apps` command, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ cf apps
Getting applications in ...
OK
name requested state instances memory disk urls
...
acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io
...
----
Once Cloud Foundry acknowledges that your application has been deployed, you should be able to find the application at the URI given.
In the preceding example, you could find it at `\https://acloudyspringtime.cfapps.io/`.
[[cloud-deployment-cloud-foundry-services]]
==== Binding to Services
By default, metadata about the running application as well as service connection information is exposed to the application as environment variables (for example: `$VCAP_SERVICES`).
This architecture decision is due to Cloud Foundry's polyglot (any language and platform can be supported as a buildpack) nature.
Process-scoped environment variables are language agnostic.
Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring's `Environment` abstraction, as shown in the following example:
[source,java,indent=0]
----
@Component
class MyBean implements EnvironmentAware {
private String instanceId;
@Override
public void setEnvironment(Environment environment) {
this.instanceId = environment.getProperty("vcap.application.instance_id");
}
// ...
}
----
All Cloud Foundry properties are prefixed with `vcap`.
You can use `vcap` properties to access application information (such as the public URL of the application) and service information (such as database credentials).
See the {spring-boot-module-api}/cloud/CloudFoundryVcapEnvironmentPostProcessor.html['`CloudFoundryVcapEnvironmentPostProcessor`'] Javadoc for complete details.
TIP: The https://github.com/pivotal-cf/java-cfenv/[Java CFEnv] project is a better fit for tasks such as configuring a DataSource.
[[cloud-deployment-heroku]]
=== Heroku
Heroku is another popular PaaS platform.
To customize Heroku builds, you provide a `Procfile`, which provides the incantation required to deploy an application.
Heroku assigns a `port` for the Java application to use and then ensures that routing to the external URI works.
You must configure your application to listen on the correct port.
The following example shows the `Procfile` for our starter REST application:
[indent=0]
----
web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar
----
Spring Boot makes `-D` arguments available as properties accessible from a Spring `Environment` instance.
The `server.port` configuration property is fed to the embedded Tomcat, Jetty, or Undertow instance, which then uses the port when it starts up.
The `$PORT` environment variable is assigned to us by the Heroku PaaS.
This should be everything you need.
The most common deployment workflow for Heroku deployments is to `git push` the code to production, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ git push heroku master
Initializing repository, *done*.
Counting objects: 95, *done*.
Delta compression using up to 8 threads.
Compressing objects: 100% (78/78), *done*.
Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, *done*.
Total 95 (delta 31), reused 0 (delta 0)
-----> Java app detected
-----> Installing OpenJDK 1.8... *done*
-----> Installing Maven 3.3.1... *done*
-----> Installing settings.xml... *done*
-----> Executing: mvn -B -DskipTests=true clean install
[INFO] Scanning for projects...
Downloading: https://repo.spring.io/...
Downloaded: https://repo.spring.io/... (818 B at 1.8 KB/sec)
....
Downloaded: https://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec)
[INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/...
[INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ...
[INFO] ------------------------------------------------------------------------
[INFO] *BUILD SUCCESS*
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 59.358s
[INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014
[INFO] Final Memory: 20M/493M
[INFO] ------------------------------------------------------------------------
-----> Discovering process types
Procfile declares types -> *web*
-----> Compressing... *done*, 70.4MB
-----> Launching... *done*, v6
https://agile-sierra-1405.herokuapp.com/ *deployed to Heroku*
To git@heroku.com:agile-sierra-1405.git
* [new branch] master -> master
----
Your application should now be up and running on Heroku.
For more details, refer to https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku[Deploying Spring Boot Applications to Heroku].
[[cloud-deployment-openshift]]
=== OpenShift
https://www.openshift.com/[OpenShift] is the Red Hat public (and enterprise) extension of the Kubernetes container orchestration platform.
Similarly to Kubernetes, OpenShift has many options for installing Spring Boot based applications.
OpenShift has many resources describing how to deploy Spring Boot applications, including:
* https://blog.openshift.com/using-openshift-enterprise-grade-spring-boot-deployments/[Using the S2I builder]
* https://access.redhat.com/documentation/en-us/reference_architectures/2017/html-single/spring_boot_microservices_on_red_hat_openshift_container_platform_3/[Architecture guide]
* https://blog.openshift.com/using-spring-boot-on-openshift/[Running as a traditional web application on Wildfly]
* https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/[OpenShift Commons Briefing]
[[cloud-deployment-aws]]
=== Amazon Web Services (AWS)
Amazon Web Services offers multiple ways to install Spring Boot-based applications, either as traditional web applications (war) or as executable jar files with an embedded web server.
The options include:
* AWS Elastic Beanstalk
* AWS Code Deploy
* AWS OPS Works
* AWS Cloud Formation
* AWS Container Registry
Each has different features and pricing models.
In this document, we describe only the simplest option: AWS Elastic Beanstalk.
==== AWS Elastic Beanstalk
As described in the official https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html[Elastic Beanstalk Java guide], there are two main options to deploy a Java application.
You can either use the "`Tomcat Platform`" or the "`Java SE platform`".
===== Using the Tomcat Platform
This option applies to Spring Boot projects that produce a war file.
No special configuration is required.
You need only follow the official guide.
===== Using the Java SE Platform
This option applies to Spring Boot projects that produce a jar file and run an embedded web container.
Elastic Beanstalk environments run an nginx instance on port 80 to proxy the actual application, running on port 5000.
To configure it, add the following line to your `application.properties` file:
[indent=0]
----
server.port=5000
----
[TIP]
.Upload binaries instead of sources
====
By default, Elastic Beanstalk uploads sources and compiles them in AWS.
However, it is best to upload the binaries instead.
To do so, add lines similar to the following to your `.elasticbeanstalk/config.yml` file:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
deploy:
artifact: target/demo-0.0.1-SNAPSHOT.jar
----
====
[TIP]
.Reduce costs by setting the environment type
====
By default an Elastic Beanstalk environment is load balanced.
The load balancer has a significant cost.
To avoid that cost, set the environment type to "`Single instance`", as described in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity[the Amazon documentation].
You can also create single instance environments by using the CLI and the following command:
[indent=0]
----
eb create -s
----
====
==== Summary
This is one of the easiest ways to get to AWS, but there are more things to cover, such as how to integrate Elastic Beanstalk into any CI / CD tool, use the Elastic Beanstalk Maven plugin instead of the CLI, and others.
There is a https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/[blog post] covering these topics more in detail.
[[cloud-deployment-boxfuse]]
=== Boxfuse and Amazon Web Services
https://boxfuse.com/[Boxfuse] works by turning your Spring Boot executable jar or war into a minimal VM image that can be deployed unchanged either on VirtualBox or on AWS.
Boxfuse comes with deep integration for Spring Boot and uses the information from your Spring Boot configuration file to automatically configure ports and health check URLs.
Boxfuse leverages this information both for the images it produces as well as for all the resources it provisions (instances, security groups, elastic load balancers, and so on).
Once you have created a https://console.boxfuse.com[Boxfuse account], connected it to your AWS account, installed the latest version of the Boxfuse Client, and ensured that the application has been built by Maven or Gradle (by using, for example, `mvn clean package`), you can deploy your Spring Boot application to AWS with a command similar to the following:
[indent=0]
----
$ boxfuse run myapp-1.0.jar -env=prod
----
See the https://boxfuse.com/docs/commandline/run.html[`boxfuse run` documentation] for more options.
If there is a https://boxfuse.com/docs/commandline/#configuration[`boxfuse.conf`] file present in the current directory, it is considered.
TIP: By default, Boxfuse activates a Spring profile named `boxfuse` on startup.
If your executable jar or war contains an https://boxfuse.com/docs/payloads/springboot.html#configuration[`application-boxfuse.properties`] file, Boxfuse bases its configuration on the properties it contains.
At this point, `boxfuse` creates an image for your application, uploads it, and configures and starts the necessary resources on AWS, resulting in output similar to the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
Fusing Image for myapp-1.0.jar ...
Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0
Creating axelfontaine/myapp ...
Pushing axelfontaine/myapp:1.0 ...
Verifying axelfontaine/myapp:1.0 ...
Creating Elastic IP ...
Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ...
Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ...
AMI created in 00:23.557s -> ami-d23f38cf
Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ...
Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ...
Instance launched in 00:30.306s -> i-92ef9f53
Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at https://52.28.235.61/ ...
Payload started in 00:29.266s -> https://52.28.235.61/
Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ...
Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ...
Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at https://myapp-axelfontaine.boxfuse.io/
----
Your application should now be up and running on AWS.
See the blog post on https://boxfuse.com/blog/spring-boot-ec2.html[deploying Spring Boot apps on EC2] as well as the https://boxfuse.com/docs/payloads/springboot.html[documentation for the Boxfuse Spring Boot integration] to get started with a Maven build to run the app.
[[cloud-deployment-gae]]
=== Google Cloud
Google Cloud has several options that can be used to launch Spring Boot applications.
The easiest to get started with is probably App Engine, but you could also find ways to run Spring Boot in a container with Container Engine or on a virtual machine with Compute Engine.
To run in App Engine, you can create a project in the UI first, which sets up a unique identifier for you and also sets up HTTP routes.
Add a Java app to the project and leave it empty and then use the https://cloud.google.com/sdk/install[Google Cloud SDK] to push your Spring Boot app into that slot from the command line or CI build.
App Engine Standard requires you to use WAR packaging.
Follow https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/appengine-standard-java8/springboot-appengine-standard/README.md[these steps] to deploy App Engine Standard application to Google Cloud.
Alternatively, App Engine Flex requires you to create an `app.yaml` file to describe the resources your app requires.
Normally, you put this file in `src/main/appengine`, and it should resemble the following file:
[source,yaml,indent=0]
----
service: default
runtime: java
env: flex
runtime_config:
jdk: openjdk8
handlers:
- url: /.*
script: this field is required, but ignored
manual_scaling:
instances: 1
health_check:
enable_health_check: False
env_variables:
ENCRYPT_KEY: your_encryption_key_here
----
You can deploy the app (for example, with a Maven plugin) by adding the project ID to the build configuration, as shown in the following example:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>1.3.0</version>
<configuration>
<project>myproject</project>
</configuration>
</plugin>
----
Then deploy with `mvn appengine:deploy` (if you need to authenticate first, the build fails).
[[deployment-install]]
== Installing Spring Boot Applications
In addition to running Spring Boot applications by using `java -jar`, it is also possible to make fully executable applications for Unix systems.
A fully executable jar can be executed like any other executable binary or it can be <<deployment-service,registered with `init.d` or `systemd`>>.
This makes it very easy to install and manage Spring Boot applications in common production environments.
CAUTION: Fully executable jars work by embedding an extra script at the front of the file.
Currently, some tools do not accept this format, so you may not always be able to use this technique.
For example, `jar -xf` may silently fail to extract a jar or war that has been made fully executable.
It is recommended that you make your jar or war fully executable only if you intend to execute it directly, rather than running it with `java -jar` or deploying it to a servlet container.
CAUTION: A zip64-format jar file cannot be made fully executable.
Attempting to do so will result in a jar file that is reported as corrupt when executed directly or with `java -jar`.
A standard-format jar file that contains one or more zip64-format nested jars can be fully executable.
To create a '`fully executable`' jar with Maven, use the following plugin configuration:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
----
The following example shows the equivalent Gradle configuration:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
----
bootJar {
launchScript()
}
----
You can then run your application by typing `./my-application.jar` (where `my-application` is the name of your artifact).
The directory containing the jar is used as your application's working directory.
[[deployment-install-supported-operating-systems]]
=== Supported Operating Systems
The default script supports most Linux distributions and is tested on CentOS and Ubuntu.
Other platforms, such as OS X and FreeBSD, require the use of a custom `embeddedLaunchScript`.
[[deployment-service]]
=== Unix/Linux Services
Spring Boot application can be easily started as Unix/Linux services by using either `init.d` or `systemd`.
[[deployment-initd-service]]
==== Installation as an `init.d` Service (System V)
If you configured Spring Boot's Maven or Gradle plugin to generate a <<deployment-install, fully executable jar>>, and you do not use a custom `embeddedLaunchScript`, your application can be used as an `init.d` service.
To do so, symlink the jar to `init.d` to support the standard `start`, `stop`, `restart`, and `status` commands.
The script supports the following features:
* Starts the services as the user that owns the jar file
* Tracks the application's PID by using `/var/run/<appname>/<appname>.pid`
* Writes console logs to `/var/log/<appname>.log`
Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as an `init.d` service, create a symlink, as follows:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp
----
Once installed, you can start and stop the service in the usual way.
For example, on a Debian-based system, you could start it with the following command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ service myapp start
----
TIP: If your application fails to start, check the log file written to `/var/log/<appname>.log` for errors.
You can also flag the application to start automatically by using your standard operating system tools.
For example, on Debian, you could use the following command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ update-rc.d myapp defaults <priority>
----
[[deployment-initd-service-securing]]
===== Securing an `init.d` Service
NOTE: The following is a set of guidelines on how to secure a Spring Boot application that runs as an init.d service.
It is not intended to be an exhaustive list of everything that should be done to harden an application and the environment in which it runs.
When executed as root, as is the case when root is being used to start an init.d service, the default executable script runs the application as the user specified in the `RUN_AS_USER` environment variable.
When the environment variable is not set, the user who owns the jar file is used instead.
You should never run a Spring Boot application as `root`, so `RUN_AS_USER` should never be root and your application's jar file should never be owned by root.
Instead, create a specific user to run your application and set the `RUN_AS_USER` environment variable or use `chown` to make it the owner of the jar file, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ chown bootapp:bootapp your-app.jar
----
In this case, the default executable script runs the application as the `bootapp` user.
TIP: To reduce the chances of the application's user account being compromised, you should consider preventing it from using a login shell.
For example, you can set the account's shell to `/usr/sbin/nologin`.
You should also take steps to prevent the modification of your application's jar file.
Firstly, configure its permissions so that it cannot be written and can only be read or executed by its owner, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ chmod 500 your-app.jar
----
Second, you should also take steps to limit the damage if your application or the account that's running it is compromised.
If an attacker does gain access, they could make the jar file writable and change its contents.
One way to protect against this is to make it immutable by using `chattr`, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ sudo chattr +i your-app.jar
----
This will prevent any user, including root, from modifying the jar.
If root is used to control the application's service and you <<deployment-script-customization-conf-file, use a `.conf` file>> to customize its startup, the `.conf` file is read and evaluated by the root user.
It should be secured accordingly.
Use `chmod` so that the file can only be read by the owner and use `chown` to make root the owner, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ chmod 400 your-app.conf
$ sudo chown root:root your-app.conf
----
[[deployment-systemd-service]]
==== Installation as a `systemd` Service
`systemd` is the successor of the System V init system and is now being used by many modern Linux distributions.
Although you can continue to use `init.d` scripts with `systemd`, it is also possible to launch Spring Boot applications by using `systemd` '`service`' scripts.
Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as a `systemd` service, create a script named `myapp.service` and place it in `/etc/systemd/system` directory.
The following script offers an example:
[indent=0]
----
[Unit]
Description=myapp
After=syslog.target
[Service]
User=myapp
ExecStart=/var/myapp/myapp.jar
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
----
IMPORTANT: Remember to change the `Description`, `User`, and `ExecStart` fields for your application.
NOTE: The `ExecStart` field does not declare the script action command, which means that the `run` command is used by default.
Note that, unlike when running as an `init.d` service, the user that runs the application, the PID file, and the console log file are managed by `systemd` itself and therefore must be configured by using appropriate fields in the '`service`' script.
Consult the https://www.freedesktop.org/software/systemd/man/systemd.service.html[service unit configuration man page] for more details.
To flag the application to start automatically on system boot, use the following command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ systemctl enable myapp.service
----
Refer to `man systemctl` for more details.
[[deployment-script-customization]]
==== Customizing the Startup Script
The default embedded startup script written by the Maven or Gradle plugin can be customized in a number of ways.
For most people, using the default script along with a few customizations is usually enough.
If you find you cannot customize something that you need to, use the `embeddedLaunchScript` option to write your own file entirely.
[[deployment-script-customization-when-it-written]]
===== Customizing the Start Script when It Is Written
It often makes sense to customize elements of the start script as it is written into the jar file.
For example, init.d scripts can provide a "`description`".
Since you know the description up front (and it need not change), you may as well provide it when the jar is generated.
To customize written elements, use the `embeddedLaunchScriptProperties` option of the Spring Boot Maven plugin or the {spring-boot-gradle-plugin-docs}/#packaging-executable-configuring-launch-script[`properties` property of the Spring Boot Gradle plugin's `launchScript`].
The following property substitutions are supported with the default script:
[cols="1,3,3,3"]
|===
| Name | Description | Gradle default | Maven default
| `mode`
| The script mode.
| `auto`
| `auto`
| `initInfoProvides`
| The `Provides` section of "`INIT INFO`"
| `${task.baseName}`
| `${project.artifactId}`
| `initInfoRequiredStart`
| `Required-Start` section of "`INIT INFO`".
| `$remote_fs $syslog $network`
| `$remote_fs $syslog $network`
| `initInfoRequiredStop`
| `Required-Stop` section of "`INIT INFO`".
| `$remote_fs $syslog $network`
| `$remote_fs $syslog $network`
| `initInfoDefaultStart`
| `Default-Start` section of "`INIT INFO`".
| `2 3 4 5`
| `2 3 4 5`
| `initInfoDefaultStop`
| `Default-Stop` section of "`INIT INFO`".
| `0 1 6`
| `0 1 6`
| `initInfoShortDescription`
| `Short-Description` section of "`INIT INFO`".
| Single-line version of `${project.description}` (falling back to `${task.baseName}`)
| `${project.name}`
| `initInfoDescription`
| `Description` section of "`INIT INFO`".
| `${project.description}` (falling back to `${task.baseName}`)
| `${project.description}` (falling back to `${project.name}`)
| `initInfoChkconfig`
| `chkconfig` section of "`INIT INFO`"
| `2345 99 01`
| `2345 99 01`
| `confFolder`
| The default value for `CONF_FOLDER`
| Folder containing the jar
| Folder containing the jar
| `inlinedConfScript`
| Reference to a file script that should be inlined in the default launch script.
This can be used to set environmental variables such as `JAVA_OPTS` before any external config files are loaded
|
|
| `logFolder`
| Default value for `LOG_FOLDER`.
Only valid for an `init.d` service
|
|
| `logFilename`
| Default value for `LOG_FILENAME`.
Only valid for an `init.d` service
|
|
| `pidFolder`
| Default value for `PID_FOLDER`.
Only valid for an `init.d` service
|
|
| `pidFilename`
| Default value for the name of the PID file in `PID_FOLDER`.
Only valid for an `init.d` service
|
|
| `useStartStopDaemon`
| Whether the `start-stop-daemon` command, when it's available, should be used to control the process
| `true`
| `true`
| `stopWaitTime`
| Default value for `STOP_WAIT_TIME` in seconds.
Only valid for an `init.d` service
| 60
| 60
|===
[[deployment-script-customization-when-it-runs]]
===== Customizing a Script When It Runs
For items of the script that need to be customized _after_ the jar has been written, you can use environment variables or a <<deployment-script-customization-conf-file, config file>>.
The following environment properties are supported with the default script:
[cols="1,6"]
|===
| Variable | Description
| `MODE`
| The "`mode`" of operation.
The default depends on the way the jar was built but is usually `auto` (meaning it tries to guess if it is an init script by checking if it is a symlink in a directory called `init.d`).
You can explicitly set it to `service` so that the `stop\|start\|status\|restart` commands work or to `run` if you want to run the script in the foreground.
| `RUN_AS_USER`
| The user that will be used to run the application.
When not set, the user that owns the jar file will be used.
| `USE_START_STOP_DAEMON`
| Whether the `start-stop-daemon` command, when it's available, should be used to control the process.
Defaults to `true`.
| `PID_FOLDER`
| The root name of the pid folder (`/var/run` by default).
| `LOG_FOLDER`
| The name of the folder in which to put log files (`/var/log` by default).
| `CONF_FOLDER`
| The name of the folder from which to read .conf files (same folder as jar-file by default).
| `LOG_FILENAME`
| The name of the log file in the `LOG_FOLDER` (`<appname>.log` by default).
| `APP_NAME`
| The name of the app.
If the jar is run from a symlink, the script guesses the app name.
If it is not a symlink or you want to explicitly set the app name, this can be useful.
| `RUN_ARGS`
| The arguments to pass to the program (the Spring Boot app).
| `JAVA_HOME`
| The location of the `java` executable is discovered by using the `PATH` by default, but you can set it explicitly if there is an executable file at `$JAVA_HOME/bin/java`.
| `JAVA_OPTS`
| Options that are passed to the JVM when it is launched.
| `JARFILE`
| The explicit location of the jar file, in case the script is being used to launch a jar that it is not actually embedded.
| `DEBUG`
| If not empty, sets the `-x` flag on the shell process, making it easy to see the logic in the script.
| `STOP_WAIT_TIME`
| The time in seconds to wait when stopping the application before forcing a shutdown (`60` by default).
|===
NOTE: The `PID_FOLDER`, `LOG_FOLDER`, and `LOG_FILENAME` variables are only valid for an `init.d` service.
For `systemd`, the equivalent customizations are made by using the '`service`' script.
See the https://www.freedesktop.org/software/systemd/man/systemd.service.html[service unit configuration man page] for more details.
[[deployment-script-customization-conf-file]]
With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding section can be configured by using a `.conf` file.
The file is expected to be next to the jar file and have the same name but suffixed with `.conf` rather than `.jar`.
For example, a jar named `/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`, as shown in the following example:
.myapp.conf
[indent=0,subs="verbatim,quotes,attributes"]
----
JAVA_OPTS=-Xmx1024M
LOG_FOLDER=/custom/log/folder
----
TIP: If you do not like having the config file next to the jar file, you can set a `CONF_FOLDER` environment variable to customize the location of the config file.
To learn about securing this file appropriately, see <<deployment-initd-service-securing,the guidelines for securing an init.d service>>.
[[deployment-windows]]
=== Microsoft Windows Services
A Spring Boot application can be started as a Windows service by using https://github.com/kohsuke/winsw[`winsw`].
A (https://github.com/snicoll-scratches/spring-boot-daemon[separately maintained sample]) describes step-by-step how you can create a Windows service for your Spring Boot application.
[[deployment-whats-next]]
== What to Read Next
Check out the https://www.cloudfoundry.org/[Cloud Foundry], https://www.heroku.com/[Heroku], https://www.openshift.com[OpenShift], and https://boxfuse.com[Boxfuse] web sites for more information about the kinds of features that a PaaS can offer.
These are just four of the most popular Java PaaS providers.
Since Spring Boot is so amenable to cloud-based deployment, you can freely consider other providers as well.
The next section goes on to cover the _<<spring-boot-cli.adoc#cli, Spring Boot CLI>>_, or you can jump ahead to read about _<<build-tool-plugins.adoc#build-tool-plugins, build tool plugins>>_.

View File

@@ -0,0 +1,91 @@
[[boot-documentation]]
= Spring Boot Documentation
include::attributes.adoc[]
This section provides a brief overview of Spring Boot reference documentation.
It serves as a map for the rest of the document.
[[boot-documentation-about]]
== About the Documentation
The Spring Boot reference guide is available as:
* {spring-boot-docs}/html[Multi-page HTML]
* {spring-boot-docs}/htmlsingle[Single page HTML]
* {spring-boot-docs}/pdf/spring-boot-reference.pdf[PDF]
The latest copy is available at {spring-boot-current-docs}.
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.
[[boot-documentation-getting-help]]
== Getting Help
If you have trouble with Spring Boot, we would like to help.
* Try the <<howto.adoc#howto, How-to documents>>.
They provide solutions to the most common questions.
* Learn the Spring basics.
Spring Boot builds on many other Spring projects.
Check the https://spring.io[spring.io] web-site for a wealth of reference documentation.
If you are starting out with Spring, try one of the https://spring.io/guides[guides].
* Ask a question.
We monitor https://stackoverflow.com[stackoverflow.com] for questions tagged with https://stackoverflow.com/tags/spring-boot[`spring-boot`].
* Report bugs with Spring Boot at 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 {spring-boot-code}[get involved].
[[boot-documentation-first-steps]]
== First Steps
If you are getting started with Spring Boot or 'Spring' in general, start with <<getting-started.adoc#getting-started, the following topics>>:
* *From scratch:* <<getting-started.adoc#getting-started-introducing-spring-boot, Overview>> | <<getting-started.adoc#getting-started-system-requirements, Requirements>> | <<getting-started.adoc#getting-started-installing-spring-boot, Installation>>
* *Tutorial:* <<getting-started.adoc#getting-started-first-application, Part 1>> | <<getting-started.adoc#getting-started-first-application-code, Part 2>>
* *Running your example:* <<getting-started.adoc#getting-started-first-application-run, Part 1>> | <<getting-started.adoc#getting-started-first-application-executable-jar, Part 2>>
== Working with Spring Boot
Ready to actually start using Spring Boot? <<using-spring-boot.adoc#using-boot, We have you covered>>:
* *Build systems:* <<using-spring-boot.adoc#using-boot-maven, Maven>> | <<using-spring-boot.adoc#using-boot-gradle, Gradle>> | <<using-spring-boot.adoc#using-boot-ant, Ant>> | <<using-spring-boot.adoc#using-boot-starter, Starters>>
* *Best practices:* <<using-spring-boot.adoc#using-boot-structuring-your-code, Code Structure>> | <<using-spring-boot.adoc#using-boot-configuration-classes, @Configuration>> | <<using-spring-boot.adoc#using-boot-auto-configuration, @EnableAutoConfiguration>> | <<using-spring-boot.adoc#using-boot-spring-beans-and-dependency-injection, Beans and Dependency Injection>>
* *Running your code:* <<using-spring-boot.adoc#using-boot-running-from-an-ide, IDE>> | <<using-spring-boot.adoc#using-boot-running-as-a-packaged-application, Packaged>> | <<using-spring-boot.adoc#using-boot-running-with-the-maven-plugin, Maven>> | <<using-spring-boot.adoc#using-boot-running-with-the-gradle-plugin, Gradle>>
* *Packaging your app:* <<using-spring-boot.adoc#using-boot-packaging-for-production, Production jars>>
* *Spring Boot CLI:* <<spring-boot-cli.adoc#cli, Using the CLI>>
== Learning about Spring Boot Features
Need more details about Spring Boot's core features?
<<spring-boot-features.adoc#boot-features, The following content is for you>>:
* *Core Features:* <<spring-boot-features.adoc#boot-features-spring-application, SpringApplication>> | <<spring-boot-features.adoc#boot-features-external-config, External Configuration>> | <<spring-boot-features.adoc#boot-features-profiles, Profiles>> | <<spring-boot-features.adoc#boot-features-logging, Logging>>
* *Web Applications:* <<spring-boot-features.adoc#boot-features-spring-mvc, MVC>> | <<spring-boot-features.adoc#boot-features-embedded-container, Embedded Containers>>
* *Working with data:* <<spring-boot-features.adoc#boot-features-sql, SQL>> | <<spring-boot-features.adoc#boot-features-nosql, NO-SQL>>
* *Messaging:* <<spring-boot-features.adoc#boot-features-messaging, Overview>> | <<spring-boot-features.adoc#boot-features-jms, JMS>>
* *Testing:* <<spring-boot-features.adoc#boot-features-testing, Overview>> | <<spring-boot-features.adoc#boot-features-testing-spring-boot-applications, Boot Applications>> | <<spring-boot-features.adoc#boot-features-test-utilities, Utils>>
* *Extending:* <<spring-boot-features.adoc#boot-features-developing-auto-configuration, Auto-configuration>> | <<spring-boot-features.adoc#boot-features-condition-annotations, @Conditions>>
== Moving to Production
When you are ready to push your Spring Boot application to production, we have <<production-ready-features.adoc#production-ready, some tricks>> that you might like:
* *Management endpoints:* <<production-ready-features.adoc#production-ready-endpoints, Overview>>
* *Connection options:* <<production-ready-features.adoc#production-ready-monitoring, HTTP>> | <<production-ready-features.adoc#production-ready-jmx, JMX>>
* *Monitoring:* <<production-ready-features.adoc#production-ready-metrics, Metrics>> | <<production-ready-features.adoc#production-ready-auditing, Auditing>> | <<production-ready-features.adoc#production-ready-http-tracing, HTTP Tracing>> | <<production-ready-features.adoc#production-ready-process-monitoring, Process>>
== Advanced Topics
Finally, we have a few topics for more advanced users:
* *Spring Boot Applications Deployment:* <<deployment.adoc#cloud-deployment, Cloud Deployment>> | <<deployment.adoc#deployment-service, OS Service>>
* *Build tool plugins:* <<build-tool-plugins.adoc#build-tool-plugins-maven-plugin, Maven>> | <<build-tool-plugins.adoc#build-tool-plugins-gradle-plugin, Gradle>>
* *Appendix:* <<appendix-application-properties.adoc#common-application-properties,Application Properties>> | <<appendix-configuration-metadata.adoc#configuration-metadata,Configuration Metadata>> | <<appendix-auto-configuration-classes.adoc#auto-configuration-classes,Auto-configuration Classes>> | <<appendix-test-auto-configuration.adoc#test-auto-configuration,Test Auto-configuration Annotations>> | <<appendix-executable-jar-format.adoc#executable-jar,Executable Jars>> | <<appendix-dependency-versions.adoc#appendex-dependency-versions,Dependency Versions>>

View File

@@ -0,0 +1,771 @@
[[getting-started]]
= Getting Started
include::attributes.adoc[]
If you are getting started with Spring Boot, or "`Spring`" in general, start by reading this section.
It answers the basic "`what?`", "`how?`" and "`why?`" questions.
It includes an introduction to Spring Boot, along with installation instructions.
We then walk you through building your first Spring Boot application, discussing some core principles as we go.
[[getting-started-introducing-spring-boot]]
== Introducing Spring Boot
Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run.
We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss.
Most Spring Boot applications need very little Spring configuration.
You can use Spring Boot to create Java applications that can be started by using `java -jar` or more traditional war deployments.
We also provide a command line tool that runs "`spring scripts`".
Our primary goals are:
* Provide a radically faster and widely accessible getting-started experience for all Spring development.
* Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
* Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).
* Absolutely no code generation and no requirement for XML configuration.
[[getting-started-system-requirements]]
== System Requirements
Spring Boot {spring-boot-version} requires https://www.java.com[Java 8] and is compatible up to Java 13 (included).
{spring-framework-docs}[Spring Framework {spring-framework-version}] or above is also required.
Explicit build support is provided for the following build tools:
|===
| Build Tool | Version
| Maven
| 3.3+
| Gradle
| 5.x and 6.x (4.10 is also supported but in a deprecated form)
|===
[[getting-started-system-requirements-servlet-containers]]
=== Servlet Containers
Spring Boot supports the following embedded servlet containers:
|===
| Name | Servlet Version
| Tomcat 9.0
| 4.0
| Jetty 9.4
| 3.1
| Undertow 2.0
| 4.0
|===
You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container.
[[getting-started-installing-spring-boot]]
== Installing Spring Boot
Spring Boot can be used with "`classic`" Java development tools or installed as a command line tool.
Either way, you need https://www.java.com[Java SDK v1.8] or higher.
Before you begin, you should check your current Java installation by using the following command:
[indent=0]
----
$ java -version
----
If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the <<getting-started-installing-the-cli, Spring Boot CLI>> (Command Line Interface) first.
Otherwise, read on for "`classic`" installation instructions.
[[getting-started-installation-instructions-for-java]]
=== Installation Instructions for the Java Developer
You can use Spring Boot in the same way as any standard Java library.
To do so, include the appropriate `+spring-boot-*.jar+` files on your classpath.
Spring Boot does not require any special tools integration, so you can use any IDE or text editor.
Also, there is nothing special about a Spring Boot application, so you can run and debug a Spring Boot application as you would any other Java program.
Although you _could_ copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).
[[getting-started-maven-installation]]
==== Maven Installation
Spring Boot is compatible with Apache Maven 3.3 or above.
If you do not already have Maven installed, you can follow the instructions at https://maven.apache.org.
TIP: On many operating systems, Maven can be installed with a package manager.
If you use OSX Homebrew, try `brew install maven`.
Ubuntu users can run `sudo apt-get install maven`.
Windows users with https://chocolatey.org/[Chocolatey] can run `choco install maven` from an elevated (administrator) prompt.
Spring Boot dependencies use the `org.springframework.boot` `groupId`.
Typically, your Maven POM file inherits from the `spring-boot-starter-parent` project and declares dependencies to one or more <<using-spring-boot.adoc#using-boot-starter,"`Starters`">>.
Spring Boot also provides an optional <<build-tool-plugins.adoc#build-tool-plugins-maven-plugin, Maven plugin>> to create executable jars.
The following listing shows a typical `pom.xml` file:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<?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>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{spring-boot-version}</version>
</parent>
<!-- Override inherited settings -->
<description/>
<developers>
<developer/>
</developers>
<licenses>
<license/>
</licenses>
<scm>
<url/>
</scm>
<url/>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
ifeval::["{spring-boot-artifactory-repo}" != "release"]
<!-- Add Spring repositories -->
<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
endif::[]
</project>
----
TIP: The `spring-boot-starter-parent` is a great way to use Spring Boot, but it might not be suitable all of the time.
Sometimes you may need to inherit from a different parent POM, or you might not like our default settings.
In those cases, see <<using-spring-boot.adoc#using-boot-maven-without-a-parent>> for an alternative solution that uses an `import` scope.
[[getting-started-gradle-installation]]
==== Gradle Installation
Spring Boot is compatible with 5.x and 6.x.
4.10 is also supported but this support is deprecated and will be removed in a future release.
If you do not already have Gradle installed, you can follow the instructions at https://gradle.org.
Spring Boot dependencies can be declared by using the `org.springframework.boot` `group`.
Typically, your project declares dependencies to one or more <<using-spring-boot.adoc#using-boot-starter, "`Starters`">>.
Spring Boot provides a useful <<build-tool-plugins.adoc#build-tool-plugins-gradle-plugin, Gradle plugin>> that can be used to simplify dependency declarations and to create executable jars.
.Gradle Wrapper
****
The Gradle Wrapper provides a nice way of "`obtaining`" Gradle when you need to build a project.
It is a small script and library that you commit alongside your code to bootstrap the build process.
See {gradle-docs}/gradle_wrapper.html for details.
****
More details on getting started with Spring Boot and Gradle can be found in the {spring-boot-gradle-plugin-docs}/#getting-started[Getting Started section] of the Gradle plugin's reference guide.
[[getting-started-installing-the-cli]]
=== Installing the Spring Boot CLI
The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to quickly prototype with Spring.
It lets you run http://groovy-lang.org/[Groovy] scripts, which means that you have a familiar Java-like syntax without so much boilerplate code.
You do not need to use the CLI to work with Spring Boot, but it is definitely the quickest way to get a Spring application off the ground.
[[getting-started-manual-cli-installation]]
==== Manual Installation
You can download the Spring CLI distribution from the Spring software repository:
* https://repo.spring.io/{spring-boot-artifactory-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.zip[spring-boot-cli-{spring-boot-version}-bin.zip]
* https://repo.spring.io/{spring-boot-artifactory-repo}/org/springframework/boot/spring-boot-cli/{spring-boot-version}/spring-boot-cli-{spring-boot-version}-bin.tar.gz[spring-boot-cli-{spring-boot-version}-bin.tar.gz]
Cutting edge
https://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/[snapshot distributions] are also available.
Once downloaded, follow the {github-raw}/spring-boot-project/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] instructions from the unpacked archive.
In summary, there is a `spring` script (`spring.bat` for Windows) in a `bin/` directory in the `.zip` file.
Alternatively, you can use `java -jar` with the `.jar` file (the script helps you to be sure that the classpath is set correctly).
[[getting-started-sdkman-cli-installation]]
==== Installation with SDKMAN!
SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI.
Get SDKMAN! from https://sdkman.io and install Spring Boot by using the following commands:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ sdk install springboot
$ spring --version
Spring Boot v{spring-boot-version}
----
If you develop features for the CLI and want easy access to the version you built, use the following commands:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-{spring-boot-version}-bin/spring-{spring-boot-version}/
$ sdk default springboot dev
$ spring --version
Spring CLI v{spring-boot-version}
----
The preceding instructions install a local instance of `spring` called the `dev` instance.
It points at your target build location, so every time you rebuild Spring Boot, `spring` is up-to-date.
You can see it by running the following command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ sdk ls springboot
================================================================================
Available Springboot Versions
================================================================================
> + dev
* {spring-boot-version}
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
----
[[getting-started-homebrew-cli-installation]]
==== OSX Homebrew Installation
If you are on a Mac and use https://brew.sh/[Homebrew], you can install the Spring Boot CLI by using the following commands:
[indent=0]
----
$ brew tap pivotal/tap
$ brew install springboot
----
Homebrew installs `spring` to `/usr/local/bin`.
NOTE: If you do not see the formula, your installation of brew might be out-of-date.
In that case, run `brew update` and try again.
[[getting-started-macports-cli-installation]]
==== MacPorts Installation
If you are on a Mac and use https://www.macports.org/[MacPorts], you can install the Spring Boot CLI by using the following command:
[indent=0]
----
$ sudo port install spring-boot-cli
----
[[getting-started-cli-command-line-completion]]
==== Command-line Completion
The Spring Boot CLI includes scripts that provide command completion for the https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29[BASH] and https://en.wikipedia.org/wiki/Z_shell[zsh] shells.
You can `source` the script (also named `spring`) in any shell or put it in your personal or system-wide bash completion initialization.
On a Debian system, the system-wide scripts are in `/shell-completion/bash` and all scripts in that directory are executed when a new shell starts.
For example, to run the script manually if you have installed by using SDKMAN!, use the following commands:
[indent=0]
----
$ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring
$ spring <HIT TAB HERE>
grab help jar run test version
----
NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line completion scripts are automatically registered with your shell.
[[getting-started-scoop-cli-installation]]
==== Windows Scoop Installation
If you are on a Windows and use https://scoop.sh/[Scoop], you can install the Spring Boot CLI by using the following commands:
[indent=0]
----
> scoop bucket add extras
> scoop install springboot
----
Scoop installs `spring` to `~/scoop/apps/springboot/current/bin`.
NOTE: If you do not see the app manifest, your installation of scoop might be out-of-date.
In that case, run `scoop update` and try again.
[[getting-started-cli-example]]
==== Quick-start Spring CLI Example
You can use the following web application to test your installation.
To start, create a file called `app.groovy`, as follows:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
----
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
----
Then run it from a shell, as follows:
[indent=0]
----
$ spring run app.groovy
----
NOTE: The first run of your application is slow, as dependencies are downloaded.
Subsequent runs are much quicker.
Open `http://localhost:8080` in your favorite web browser.
You should see the following output:
[indent=0]
----
Hello World!
----
[[getting-started-upgrading-from-an-earlier-version]]
=== Upgrading from an Earlier Version of Spring Boot
If you are upgrading from the `1.x` release of Spring Boot, check the {github-wiki}/Spring-Boot-2.0-Migration-Guide["`migration guide`" on the project wiki] that provides detailed upgrade instructions.
Check also the {github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each 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:
[source,xml,indent=0]
----
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
----
WARNING: Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account.
NOTE: Once you're done with the migration, please make sure to remove this module from your project's dependencies.
To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`).
If you manually installed the CLI, follow the <<getting-started-manual-cli-installation, standard instructions>>, remembering to update your `PATH` environment variable to remove any older references.
[[getting-started-first-application]]
== Developing Your First Spring Boot Application
This section describes how to develop a simple "`Hello World!`" web application that highlights some of Spring Boot's key features.
We use Maven to build this project, since most IDEs support it.
[TIP]
====
The https://spring.io[spring.io] web site contains many "`Getting Started`" https://spring.io/guides[guides] that use Spring Boot.
If you need to solve a specific problem, check there first.
You can shortcut the steps below by going to https://start.spring.io and choosing the "Web" starter from the dependencies searcher.
Doing so generates a new project structure so that you can <<getting-started-first-application-code,start coding right away>>.
Check the {spring-initializr-docs}/#user-guide[Spring Initializr documentation] for more details.
====
Before we begin, open a terminal and run the following commands to ensure that you have valid versions of Java and Maven installed:
[indent=0]
----
$ 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)
----
[indent=0]
----
$ 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
----
NOTE: This sample needs to be created in its own folder.
Subsequent instructions assume that you have created a suitable folder and that it is your current directory.
[[getting-started-first-application-pom]]
=== Creating the POM
We need to start by creating a Maven `pom.xml` file.
The `pom.xml` is the recipe that is used to build your project.
Open your favorite text editor and add the following:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<?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>{spring-boot-version}</version>
</parent>
<description/>
<developers>
<developer/>
</developers>
<licenses>
<license/>
</licenses>
<scm>
<url/>
</scm>
<url/>
<!-- Additional lines to be added here... -->
ifeval::["{spring-boot-artifactory-repo}" != "release"]
<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
endif::[]
</project>
----
The preceding listing should give you a working build.
You can test it by running `mvn package` (for now, you can ignore the "`jar will be empty - no content was marked for inclusion!`" warning).
NOTE: At this point, you could import the project into an IDE (most modern Java IDEs include built-in support for Maven).
For simplicity, we continue to use a plain text editor for this example.
[[getting-started-first-application-dependencies]]
=== Adding Classpath Dependencies
Spring Boot provides a number of "`Starters`" that let you add jars to your classpath.
Our applications for smoke tests use the `spring-boot-starter-parent` in the `parent` section of the POM.
The `spring-boot-starter-parent` is a special starter that provides useful Maven defaults.
It also provides a <<using-spring-boot.adoc#using-boot-dependency-management,`dependency-management`>> section so that you can omit `version` tags for "`blessed`" dependencies.
Other "`Starters`" provide dependencies that you are likely to need when developing a specific type of application.
Since we are developing a web application, we add a `spring-boot-starter-web` dependency.
Before that, we can look at what we currently have by running the following command:
[indent=0]
----
$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
----
The `mvn dependency:tree` command prints a tree representation of your project dependencies.
You can see that `spring-boot-starter-parent` provides no dependencies by itself.
To add the necessary dependencies, edit your `pom.xml` and add the `spring-boot-starter-web` dependency immediately below the `parent` section:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
----
If you run `mvn dependency:tree` again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself.
[[getting-started-first-application-code]]
=== Writing the Code
To finish our application, we need to create a single Java file.
By default, Maven compiles sources from `src/main/java`, so you need to create that folder structure and then add a file named `src/main/java/Example.java` to contain the following code:
[source,java,indent=0]
----
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
----
Although there is not much code here, quite a lot is going on.
We step through the important parts in the next few sections.
[[getting-started-first-application-annotations]]
==== The @RestController and @RequestMapping Annotations
The first annotation on our `Example` class is `@RestController`.
This is known as a _stereotype_ annotation.
It provides hints for people reading the code and for Spring that the class plays a specific role.
In this case, our class is a web `@Controller`, so Spring considers it when handling incoming web requests.
The `@RequestMapping` annotation provides "`routing`" information.
It tells Spring that any HTTP request with the `/` path should be mapped to the `home` method.
The `@RestController` annotation tells Spring to render the resulting string directly back to the caller.
TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations (they are not specific to Spring Boot).
See the {spring-framework-docs}web.html#mvc[MVC section] in the Spring Reference Documentation for more details.
[[getting-started-first-application-auto-configuration]]
==== The @EnableAutoConfiguration Annotation
The second class-level annotation is `@EnableAutoConfiguration`.
This annotation tells Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies that you have added.
Since `spring-boot-starter-web` added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.
.Starters and Auto-configuration
****
Auto-configuration is designed to work well with "`Starters`", but the two concepts are not directly tied.
You are free to pick and choose jar dependencies outside of the starters.
Spring Boot still does its best to auto-configure your application.
****
[[getting-started-first-application-main-method]]
==== The "`main`" Method
The final part of our application is the `main` method.
This is just a standard method that follows the Java convention for an application entry point.
Our main method delegates to Spring Boot's `SpringApplication` class by calling `run`.
`SpringApplication` bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.
We need to pass `Example.class` as an argument to the `run` method to tell `SpringApplication` which is the primary Spring component.
The `args` array is also passed through to expose any command-line arguments.
[[getting-started-first-application-run]]
=== Running the Example
At this point, your application should work.
Since you used the `spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start the application.
Type `mvn spring-boot:run` from the root project directory to start the application.
You should see output similar to the following:
[indent=0,subs="attributes"]
----
$ mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v{spring-boot-version})
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)
----
If you open a web browser to `http://localhost:8080`, you should see the following output:
[indent=0]
----
Hello World!
----
To gracefully exit the application, press `ctrl-c`.
[[getting-started-first-application-executable-jar]]
=== Creating an Executable Jar
We finish our example by creating a completely self-contained executable jar file that we could run in production.
Executable jars (sometimes called "`fat jars`") are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.
.Executable jars and Java
****
Java does not provide a standard way to load nested jar files (jar files that are themselves contained within a jar).
This can be problematic if you are looking to distribute a self-contained application.
To solve this problem, many developers use "`uber`" jars.
An uber jar packages all the classes from all the application's dependencies into a single archive.
The problem with this approach is that it becomes hard to see which libraries are in your application.
It can also be problematic if the same filename is used (but with different content) in multiple jars.
Spring Boot takes a <<appendix-executable-jar-format.adoc#executable-jar, different approach>> and lets you actually nest jars directly.
****
To create an executable jar, we need to add the `spring-boot-maven-plugin` to our `pom.xml`.
To do so, insert the following lines just below the `dependencies` section:
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
----
NOTE: The `spring-boot-starter-parent` POM includes `<executions>` configuration to bind the `repackage` goal.
If you do not use the parent POM, you need to declare this configuration yourself.
See the {spring-boot-maven-plugin-docs}/usage.html[plugin documentation] for details.
Save your `pom.xml` and run `mvn package` from the command line, as follows:
[indent=0,subs="attributes"]
----
$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:{spring-boot-version}:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
----
If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`.
The file should be around 10 MB in size.
If you want to peek inside, you can use `jar tvf`, as follows:
[indent=0]
----
$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar
----
You should also see a much smaller file named `myproject-0.0.1-SNAPSHOT.jar.original` in the `target` directory.
This is the original jar file that Maven created before it was repackaged by Spring Boot.
To run that application, use the `java -jar` command, as follows:
[indent=0,subs="attributes"]
----
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v{spring-boot-version})
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)
----
As before, to exit the application, press `ctrl-c`.
[[getting-started-whats-next]]
== What to Read Next
Hopefully, this section provided some of the Spring Boot basics and got you on your way to writing your own applications.
If you are a task-oriented type of developer, you might want to jump over to https://spring.io and check out some of the https://spring.io/guides/[getting started] guides that solve specific "`How do I do that with Spring?`" problems.
We also have Spring Boot-specific "`<<howto.adoc#howto, How-to>>`" reference documentation.
Otherwise, the next logical step is to read _<<using-spring-boot.adoc#using-boot>>_.
If you are really impatient, you could also jump ahead and read about _<<spring-boot-features.adoc#boot-features, Spring Boot features>>_.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
<productname>Spring Boot</productname>
<releaseinfo>{spring-boot-version}</releaseinfo>
<copyright>
<year>2012-2020</year>
</copyright>
<legalnotice>
<para>
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.
</para>
</legalnotice>

View File

@@ -0,0 +1,28 @@
[[spring-boot-reference-documentation]]
= Spring Boot Reference Documentation
Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch, Andy Wilkinson, Marcel Overdijk, Christian Dupuis, Sébastien Deleuze, Michael Simons, Vedran Pavić, Jay Bryant, Madhura Bhave, Eddú Meléndez
:docinfo: shared
The reference documentation consists of the following sections:
[horizontal]
<<legal.adoc#legal,Legal>> :: Legal information.
<<documentation-overview.adoc#boot-documentation,Documentation Overview>> :: About the Documentation, Getting Help, First Steps, and more.
<<getting-started.adoc#getting-started,Getting Started>> :: Introducing Spring Boot, System Requirements, Servlet Containers, Installing Spring Boot, Developing Your First Spring Boot Application
<<using-spring-boot.adoc#using-boot,Using Spring Boot>> :: Build Systems, Structuring Your Code, Configuration, Spring Beans and Dependency Injection, and more.
<<spring-boot-features.adoc#boot-features,Spring Boot Features>> :: Profiles, Logging, Security, Caching, Spring Integration, Testing, and more.
<<production-ready-features.adoc#production-ready,Spring Boot Actuator>> :: Monitoring, Metrics, Auditing, and more.
<<deployment.adoc#deployment,Deploying Spring Boot Applications>> :: Deploying to the Cloud, Installing as a Unix application.
<<spring-boot-cli.adoc#cli,Spring Boot CLI>> :: Installing the CLI, Using the CLI, Configuring the CLI, and more.
<<build-tool-plugins.adoc#build-tool-plugins,Build Tool Plugins>> :: Maven Plugin, Gradle Plugin, Antlib, and more.
<<howto.adoc#howto,"`How-to`" Guides>> :: Application Development, Configuration, Embedded Servers, Data Access, and many more.
The reference documentation has the following appendices:
[horizontal]
<<appendix-application-properties.adoc#common-application-properties,Application Properties>> :: Common application properties that can be used to configure your application.
<<appendix-configuration-metadata.adoc#configuration-metadata,Configuration Metadata>> :: Metadata used to describe configuration properties.
<<appendix-auto-configuration-classes.adoc#auto-configuration-classes,Auto-configuration Classes>> :: Auto-configuration classes provided by Spring Boot.
<<appendix-test-auto-configuration.adoc#test-auto-configuration,Test Auto-configuration Annotations>> :: Test-autoconfiguration annotations used to test slices of your application.
<<appendix-executable-jar-format.adoc#executable-jar,Executable Jars>> :: Spring Boot's executable jars, their launchers, and their format.
<<appendix-dependency-versions.adoc#appendix-dependency-versions,Dependency Versions>> :: Details of the dependencies that are managed by Spring Boot.

View File

@@ -0,0 +1,28 @@
[[spring-boot-reference-documentation]]
= Spring Boot Reference Documentation
Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch, Andy Wilkinson, Marcel Overdijk, Christian Dupuis, Sébastien Deleuze, Michael Simons, Vedran Pavić, Jay Bryant, Madhura Bhave
:docinfo: shared
include::attributes.adoc[]
include::legal.adoc[leveloffset=+1]
include::documentation-overview.adoc[leveloffset=+1]
include::getting-started.adoc[leveloffset=+1]
include::using-spring-boot.adoc[leveloffset=+1]
include::spring-boot-features.adoc[leveloffset=+1]
include::production-ready-features.adoc[leveloffset=+1]
include::deployment.adoc[leveloffset=+1]
include::spring-boot-cli.adoc[leveloffset=+1]
include::build-tool-plugins.adoc[leveloffset=+1]
include::howto.adoc[leveloffset=+1]
[[appendix]]
== Appendices
include::appendix-application-properties.adoc[leveloffset=+2]
include::appendix-configuration-metadata.adoc[leveloffset=+2]
include::appendix-auto-configuration-classes.adoc[leveloffset=+2]
include::appendix-test-auto-configuration.adoc[leveloffset=+2]
include::appendix-executable-jar-format.adoc[leveloffset=+2]
include::appendix-dependency-versions.adoc[leveloffset=+2]

View File

@@ -0,0 +1,11 @@
[legal]
= Legal
{spring-boot-version}
Copyright &#169; 2012-2019
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.

View File

@@ -0,0 +1,435 @@
[[cli]]
= Spring Boot CLI
include::attributes.adoc[]
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]]
== 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.adoc#getting-started-installing-the-cli>>_ in the "`Getting started`" section for comprehensive installation instructions.
[[cli-using-the-cli]]
== 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 simple help screen is displayed, as follows:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ 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:
[indent=0]
----
$ 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ spring version
Spring CLI v{spring-boot-version}
----
[[cli-run]]
=== 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
[source,groovy,indent=0,subs="verbatim,quotes,attributes"]
----
@RestController
class WebApplication {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
----
To compile and run the application, type the following command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ JAVA_OPTS=-Xmx1024m spring run hello.groovy
----
NOTE: When setting `JAVA_OPTS` on Microsoft Windows, make sure to quote the entire instruction, such as `set "JAVA_OPTS=-Xms256m -Xmx2048m"`.
Doing so ensures the values are properly passed to the process.
[[cli-deduced-grab-annotations]]
==== 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.
|===
TIP: See subclasses of {spring-boot-cli-module-code}/compiler/CompilerAutoConfiguration.java[`CompilerAutoConfiguration`] in the Spring Boot CLI source code to understand exactly how customizations are applied.
[[cli-default-grab-deduced-coordinates]]
==== 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.
NOTE: The default metadata is tied to the version of the CLI that you use.
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.
A table showing the dependencies and their versions that are included in the default metadata can be found in the <<appendix-dependency-versions.adoc#appendix-dependency-versions,appendix>>.
[[cli-default-import-statements]]
==== 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.
TIP: Many Spring annotations work without using `import` statements.
Try running your application to see what fails before adding imports.
[[cli-automatic-main-method]]
==== 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-default-grab-deduced-coordinates-custom-dependency-management]]
==== 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:
[source,groovy,indent=0]
----
@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:
[source,java,indent=0]
----
@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-multiple-source-files]]
=== 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:
[indent=0]
----
$ spring run *.groovy
----
[[cli-jar]]
=== 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:
[indent=0]
----
$ 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:
[indent=0]
----
public/**, resources/**, static/**, templates/**, META-INF/**, *
----
The default excludes are as follows:
[indent=0]
----
.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy
----
Type `spring help jar` on the command line for more information.
[[cli-init]]
=== Initialize a New Project
The `init` command lets you create a new project by using https://start.spring.io without leaving the shell, as shown in the following example:
[indent=0]
----
$ 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:
[indent=0]
----
$ 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:
[indent=0]
----
$ 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-shell]]
=== 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ spring shell
*Spring Boot* (v{spring-boot-version})
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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ version
Spring CLI v{spring-boot-version}
----
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-install-uninstall]]
=== 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ 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:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ spring uninstall --all
----
[[cli-groovy-beans-dsl]]
== Developing Applications with the Groovy Beans DSL
Spring Framework 4.0 has native support for a `beans{}` "`DSL`" (borrowed from https://grails.org/[Grails]), 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:
[source,groovy,indent=0]
----
@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-settings]]
== Configuring the CLI with `settings.xml`
The Spring Boot CLI uses Aether, Maven's dependency resolution engine, to resolve dependencies.
The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` to configure Aether.
The following configuration settings are honored by the CLI:
* Offline
* Mirrors
* Servers
* Proxies
* Profiles
** Activation
** Repositories
* Active profiles
See https://maven.apache.org/settings.html[Maven's settings documentation] for further information.
[[cli-whats-next]]
== What to Read Next
There are some {spring-boot-code}/spring-boot-project/spring-boot-cli/samples[sample groovy scripts] available from the GitHub repository that you can use to try out the Spring Boot CLI.
There is also extensive Javadoc throughout the {spring-boot-cli-module-code}[source code].
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.adoc#build-tool-plugins, Build tool plugins>>", which you can use with Gradle or Maven.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
[[spring-boot-reference-documentation]]
= Spring Boot Reference Documentation
Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch, Andy Wilkinson, Marcel Overdijk, Christian Dupuis, Sébastien Deleuze, Michael Simons, Vedran Pavić, Jay Bryant, Madhura Bhave
:docinfo: shared
include::attributes.adoc[]
include::legal.adoc[leveloffset=+1]
include::documentation-overview.adoc[leveloffset=+1]
include::getting-started.adoc[leveloffset=+1]
include::using-spring-boot.adoc[leveloffset=+1]
include::spring-boot-features.adoc[leveloffset=+1]
include::production-ready-features.adoc[leveloffset=+1]
include::deployment.adoc[leveloffset=+1]
include::spring-boot-cli.adoc[leveloffset=+1]
include::build-tool-plugins.adoc[leveloffset=+1]
include::howto.adoc[leveloffset=+1]
[[appendix]]
== Appendices
include::appendix-application-properties.adoc[leveloffset=+2]
include::appendix-configuration-metadata.adoc[leveloffset=+2]
include::appendix-auto-configuration-classes.adoc[leveloffset=+2]
include::appendix-test-auto-configuration.adoc[leveloffset=+2]
include::appendix-executable-jar-format.adoc[leveloffset=+2]
include::appendix-dependency-versions.adoc[leveloffset=+2]

File diff suppressed because it is too large Load Diff