Commit 64d4bf82 authored by Phillip Webb's avatar Phillip Webb

Reformat documentation to one sentence per line

Update reference documentation to use one sentence per line formatting
as recommended by the Asciidoctor team.

Closes gh-12445
parent aa632610
...@@ -2,20 +2,16 @@ ...@@ -2,20 +2,16 @@
[appendix] [appendix]
[[common-application-properties]] [[common-application-properties]]
== Common application properties == Common application properties
Various properties can be specified inside your `application.properties` file, inside Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches.
your `application.yml` file, or as command line switches. This appendix provides a list This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume them.
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, 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>>.
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 NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
should not consider this an exhaustive list. Also, you can define your own properties. Also, you can define your own properties.
WARNING: This sample file is meant as a guide only. Do **not** copy and paste the entire WARNING: This sample file is meant as a guide only. Do **not** copy and paste the entire content into your application.
content into your application. Rather, pick only the properties that you need. Rather, pick only the properties that you need.
[source,properties,indent=0,subs="verbatim,attributes,macros"] [source,properties,indent=0,subs="verbatim,attributes,macros"]
......
[appendix] [appendix]
[[auto-configuration-classes]] [[auto-configuration-classes]]
== Auto-configuration classes == Auto-configuration classes
Here is a list of all auto-configuration classes provided by Spring Boot, with links to Here is a list of all auto-configuration classes provided by Spring Boot, with links to documentation and source code.
documentation and source code. Remember to also look at the conditions report in your Remember to also look at the conditions report in your application for more details of which features are switched on.
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).
(To do so, start the app with `--debug` or `-Ddebug` or, in an Actuator application, use
the `conditions` endpoint).
......
[appendix] [appendix]
[[configuration-metadata]] [[configuration-metadata]]
== Configuration Metadata == Configuration Metadata
Spring Boot jars include metadata files that provide details of all supported Spring Boot jars include metadata files that provide details of all supported configuration properties.
configuration properties. The files are designed to let IDE developers offer 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.
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 The majority of the metadata file is generated automatically at compile time by processing all items annotated with `@ConfigurationProperties`.
processing all items annotated with `@ConfigurationProperties`. However, it is possible However, it is possible to <<configuration-metadata-additional-metadata,write part of the metadata manually>> for corner cases or more advanced use cases.
to <<configuration-metadata-additional-metadata,write part of the metadata manually>>
for corner cases or more advanced use cases.
[[configuration-metadata-format]] [[configuration-metadata-format]]
=== Metadata Format === Metadata Format
Configuration metadata files are located inside jars under Configuration metadata files are located inside jars under `META-INF/spring-configuration-metadata.json`.
`META-INF/spring-configuration-metadata.json` They use a simple JSON format with items 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:
categorized under either "`groups`" or "`properties`" and additional values hints
categorized under "hints", as shown in the following example:
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -83,8 +77,7 @@ categorized under "hints", as shown in the following example: ...@@ -83,8 +77,7 @@ categorized under "hints", as shown in the following example:
---- ----
Each "`property`" is a configuration item that the user specifies with a given value. 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 For example, `server.port` and `server.address` might be specified in `application.properties`, as follows:
`application.properties`, as follows:
[source,properties,indent=0] [source,properties,indent=0]
---- ----
...@@ -92,151 +85,136 @@ For example, `server.port` and `server.address` might be specified in ...@@ -92,151 +85,136 @@ For example, `server.port` and `server.address` might be specified in
server.address=127.0.0.1 server.address=127.0.0.1
---- ----
The "`groups`" are higher level items that do not themselves specify a value but instead The "`groups`" are higher level items that do not themselves specify a value but instead provide a contextual grouping for properties.
provide a contextual grouping for properties. For example, the `server.port` and For example, the `server.port` and `server.address` properties are part of the `server` group.
`server.address` properties are part of the `server` group.
NOTE: It is not required that every "`property`" has a "`group`". Some properties might NOTE: It is not required that every "`property`" has a "`group`". Some properties might exist in their own right.
exist in their own right.
Finally, "`hints`" are additional information used to assist the user in configuring a Finally, "`hints`" are additional information used to assist the user in configuring a given property.
given property. For example, when a developer is configuring the For example, when a developer is configuring the `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.
`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]] [[configuration-metadata-group-attributes]]
==== Group Attributes ==== Group Attributes
The JSON object contained in the `groups` array can contain the attributes shown in the The JSON object contained in the `groups` array can contain the attributes shown in the following table:
following table:
[cols="1,1,4"] [cols="1,1,4"]
|=== |===
|Name | Type |Purpose | Name | Type | Purpose
|`name` | `name`
| String | String
| The full name of the group. This attribute is mandatory. | The full name of the group. This attribute is mandatory.
|`type` | `type`
| String | String
| The class name of the data type of the group. For example, if the group were based | The class name of the data type of the group.
on a class annotated with `@ConfigurationProperties`, the attribute would contain the For example, if the group were based on a class annotated with `@ConfigurationProperties`, the attribute would contain the fully qualified name of that class.
fully qualified name of that class. If it were based on a `@Bean` method, it would be If it were based on a `@Bean` method, it would be the return type of that method.
the return type of that method. If the type is not known, the attribute may be omitted. If the type is not known, the attribute may be omitted.
|`description` | `description`
| String | String
| A short description of the group that can be displayed to users. If not description is | A short description of the group that can be displayed to users.
available, it may be omitted. It is recommended that descriptions be short paragraphs, If not description is available, it may be omitted.
with the first line providing a concise summary. The last line in the description should It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
end with a period (`.`). The last line in the description should end with a period (`.`).
|`sourceType` | `sourceType`
| String | String
| The class name of the source that contributed this group. For example, if the group | The class name of the source that contributed this group.
were based on a `@Bean` method annotated with `@ConfigurationProperties`, this attribute 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.
would contain the fully qualified name of the `@Configuration` class that contains the If the source type is not known, the attribute may be omitted.
method. If the source type is not known, the attribute may be omitted.
|`sourceMethod` | `sourceMethod`
| String | String
| The full name of the method (include parenthesis and argument types) that contributed | 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).
this group (for example, the name of a `@ConfigurationProperties` annotated `@Bean` If the source method is not known, it may be omitted.
method). If the source method is not known, it may be omitted.
|=== |===
[[configuration-metadata-property-attributes]] [[configuration-metadata-property-attributes]]
==== Property Attributes ==== Property Attributes
The JSON object contained in the `properties` array can contain the attributes described The JSON object contained in the `properties` array can contain the attributes described in the following table:
in the following table:
[cols="1,1,4"] [cols="1,1,4"]
|=== |===
|Name | Type |Purpose | Name | Type | Purpose
|`name` | `name`
| String | String
| The full name of the property. Names are in lower-case period-separated form (for | The full name of the property.
example, `server.address`). This attribute is mandatory. Names are in lower-case period-separated form (for example, `server.address`).
This attribute is mandatory.
|`type` | `type`
| String | String
| The full signature of the data type of the property (for example, `java.lang.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>`).
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.
You can use this attribute to guide the user as to the types of values that they can For consistency, the type of a primitive is specified by using its wrapper counterpart (for example, `boolean` becomes `java.lang.Boolean`).
enter. For consistency, the type of a primitive is specified by using its wrapper Note that this class may be a complex type that gets converted from a `String` as values are bound.
counterpart (for example, `boolean` becomes `java.lang.Boolean`). Note that this class If the type is not known, it may be omitted.
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`
|`description`
| String | String
| A short description of the group that can be displayed to users. If no description is | A short description of the group that can be displayed to users.
available, it may be omitted. It is recommended that descriptions be short paragraphs, If no description is available, it may be omitted.
with the first line providing a concise summary. The last line in the description should It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
end with a period (`.`). The last line in the description should end with a period (`.`).
|`sourceType` | `sourceType`
| String | String
| The class name of the source that contributed this property. For example, if the | The class name of the source that contributed this property.
property were from a class annotated with `@ConfigurationProperties`, this attribute For example, if the property were from a class annotated with `@ConfigurationProperties`, this attribute would contain the fully qualified name of that class.
would contain the fully qualified name of that class. If the source type is unknown, it If the source type is unknown, it may be omitted.
may be omitted.
|`defaultValue` | `defaultValue`
| Object | Object
| The default value, which is used if the property is not specified. If the type of the | The default value, which is used if the property is not specified.
property is an array, it can be an array of value(s). If the default value is unknown, If the type of the property is an array, it can be an array of value(s).
it may be omitted. If the default value is unknown, it may be omitted.
|`deprecation` | `deprecation`
| Deprecation | Deprecation
| Specify whether the property is deprecated. If the field is not deprecated or if that | Specify whether the property is deprecated.
information is not known, it may be omitted. The next table offers more detail about If the field is not deprecated or if that information is not known, it may be omitted.
the `deprecation` attribute. The next table offers more detail about the `deprecation` attribute.
|=== |===
The JSON object contained in the `deprecation` attribute of each `properties` element can The JSON object contained in the `deprecation` attribute of each `properties` element can contain the following attributes:
contain the following attributes:
[cols="1,1,4"] [cols="1,1,4"]
|=== |===
|Name | Type |Purpose | 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.
|`level` | `reason`
|String | String
|The level of deprecation, which can be either `warning` (the default) or `error`. When a | A short description of the reason why the property was deprecated.
property has a `warning` deprecation level, it should still be bound in the environment. If no reason is available, it may be omitted.
However, when it has an `error` deprecation level, the property is no longer managed and It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
is not bound. The last line in the description should end with a period (`.`).
|`reason` | `replacement`
|String | String
|A short description of the reason why the property was deprecated. If no reason is | The full name of the property that _replaces_ this deprecated property.
available, it may be omitted. It is recommended that descriptions be short paragraphs, If there is no replacement for this property, it may be omitted.
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 NOTE: Prior to Spring Boot 1.3, a single `deprecated` boolean attribute can be used instead of the `deprecation` element.
instead of the `deprecation` element. This is still supported in a deprecated fashion and This is still supported in a deprecated fashion and should no longer be used.
should no longer be used. If no reason and replacement are available, an empty If no reason and replacement are available, an empty `deprecation` object should be set.
`deprecation` object should be set.
Deprecation can also be specified declaratively in code by adding the Deprecation can also be specified declaratively in code by adding the `@DeprecatedConfigurationProperty` annotation to the getter exposing the deprecated property.
`@DeprecatedConfigurationProperty` annotation to the getter exposing the deprecated For instance, assume that the `app.acme.target` property was confusing and was renamed to `app.acme.name`.
property. For instance, assume that the `app.acme.target` property was confusing and The following example shows how to handle that situation:
was renamed to `app.acme.name`. The following example shows how to handle that situation:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -262,119 +240,103 @@ was renamed to `app.acme.name`. The following example shows how to handle that s ...@@ -262,119 +240,103 @@ was renamed to `app.acme.name`. The following example shows how to handle that s
} }
---- ----
NOTE: There is no way to set a `level`. `warning` is always assumed, since code is still NOTE: There is no way to set a `level`.
handling the property. `warning` is always assumed, since code is still handling the property.
The preceding code makes sure that the deprecated property still works (delegating The preceding code makes sure that the deprecated property still works (delegating to the `name` property behind the scenes).
to the `name` property behind the scenes). Once the `getTarget` and `setTarget` Once the `getTarget` and `setTarget` methods can be removed from your public API, the automatic deprecation hint in the metadata goes away as well.
methods can be removed from your public API, the automatic deprecation hint in the If you want to keep a hint, adding manual metadata with an `error` deprecation level ensures that users are still informed about that property.
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. Doing so is particularly useful when a `replacement` is provided.
[[configuration-metadata-hints-attributes]] [[configuration-metadata-hints-attributes]]
==== Hint Attributes ==== Hint Attributes
The JSON object contained in the `hints` array can contain the attributes shown in the The JSON object contained in the `hints` array can contain the attributes shown in the following table:
following table:
[cols="1,1,4"] [cols="1,1,4"]
|=== |===
|Name | Type |Purpose | Name | Type | Purpose
|`name` | `name`
| String | String
| The full name of the property to which this hint refers. Names are in lower-case | The full name of the property to which this hint refers.
period-separated form (such as `spring.mvc.servlet.path`). If the property refers to a map Names are in lower-case period-separated form (such as `spring.mvc.servlet.path`).
(such as `system.contexts`), the hint either applies to the _keys_ of the map If the property refers to a map (such as `system.contexts`), the hint either applies to the _keys_ of the map (`system.context.keys`) or the _values_ (`system.context.values`) of the map.
(`system.context.keys`) or the _values_ (`system.context.values`) of the map. This This attribute is mandatory.
attribute is mandatory.
|`values` | `values`
| ValueHint[] | ValueHint[]
| A list of valid values as defined by the `ValueHint` object (described in the next | A list of valid values as defined by the `ValueHint` object (described in the next table).
table). Each entry defines the value and may have a description. Each entry defines the value and may have a description.
|`providers` | `providers`
| ValueProvider[] | ValueProvider[]
| A list of providers as defined by the `ValueProvider` object (described later in this | A list of providers as defined by the `ValueProvider` object (described later in this document).
document). Each entry defines the name of the provider and its parameters, if any. 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 JSON object contained in the `values` attribute of each `hint` element can contain the attributes described in the following table:
the attributes described in the following table:
[cols="1,1,4"] [cols="1,1,4"]
|=== |===
|Name | Type |Purpose | Name | Type | Purpose
|`value` | `value`
| Object | Object
| A valid value for the element to which the hint refers. If the type of the property is | A valid value for the element to which the hint refers.
an array, it can also be an array of value(s). This attribute is mandatory. If the type of the property is an array, it can also be an array of value(s).
This attribute is mandatory.
|`description` | `description`
| String | String
| A short description of the value that can be displayed to users. If no description is | A short description of the value that can be displayed to users.
available, it may be omitted . It is recommended that descriptions be short paragraphs, If no description is available, it may be omitted.
with the first line providing a concise summary. The last line in the description should It is recommended that descriptions be short paragraphs, with the first line providing a concise summary.
end with a period (`.`). 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 JSON object contained in the `providers` attribute of each `hint` element can contain the attributes described in the following table:
the attributes described in the following table:
[cols="1,1,4"] [cols="1,1,4"]
|=== |===
|Name | Type |Purpose |Name | Type |Purpose
|`name` | `name`
| String | String
| The name of the provider to use to offer additional content assistance for the element | The name of the provider to use to offer additional content assistance for the element to which the hint refers.
to which the hint refers.
|`parameters` | `parameters`
| JSON object | JSON object
| Any additional parameter that the provider supports (check the documentation of the | Any additional parameter that the provider supports (check the documentation of the provider for more details).
provider for more details).
|=== |===
[[configuration-metadata-repeated-items]] [[configuration-metadata-repeated-items]]
==== Repeated Metadata Items ==== Repeated Metadata Items
Objects with the same "`property`" and "`group`" name can appear multiple times within a 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.
metadata file. For example, you could bind two separate classes to the same prefix, with 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.
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]] [[configuration-metadata-providing-manual-hints]]
=== Providing Manual Hints === Providing Manual Hints
To improve the user experience and further assist the user in configuring a given To improve the user experience and further assist the user in configuring a given property, you can provide additional metadata that:
property, you can provide additional metadata that:
* Describes the list of potential values for a property. * 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 * 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.
can discover the list of potential values based on the project's context.
==== Value Hint ==== Value Hint
The `name` attribute of each hint refers to the `name` of a property. In the The `name` attribute of each hint refers to the `name` of a property.
<<configuration-metadata-format,initial example shown earlier>>, we provide five values 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`.
for the `spring.jpa.hibernate.ddl-auto` property: `none`, `validate`, `update`, `create`, Each value may have a description as well.
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 If your property is of type `Map`, you can provide hints for both the keys and the values (but not for the map itself).
values (but not for the map itself). The special `.keys` and `.values` suffixes must The special `.keys` and `.values` suffixes must refer to the keys and the values, respectively.
refer to the keys and the values, respectively.
Assume a `sample.contexts` maps magic `String` values to an integer, as shown in the Assume a `sample.contexts` maps magic `String` values to an integer, as shown in the following example:
following example:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -386,9 +348,8 @@ following example: ...@@ -386,9 +348,8 @@ following example:
} }
---- ----
The magic values are (in this example) are `sample1` and `sample2`. In order to offer The magic values are (in this example) are `sample1` and `sample2`.
additional content assistance for the keys, you could add the following JSON to 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>>:
<<configuration-metadata-additional-metadata,the manual metadata of the module>>:
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -407,66 +368,59 @@ additional content assistance for the keys, you could add the following JSON to ...@@ -407,66 +368,59 @@ additional content assistance for the keys, you could add the following JSON to
]} ]}
---- ----
TIP: We recommend that you use an `Enum` for those two values instead. If your IDE TIP: We recommend that you use an `Enum` for those two values instead.
supports it, this is by far the most effective approach to auto-completion. If your IDE supports it, this is by far the most effective approach to auto-completion.
==== Value Providers ==== Value Providers
Providers are a powerful way to attach semantics to a property. In this section, we Providers are a powerful way to attach semantics to a property.
define the official providers that you can use for your own hints. However, your favorite In this section, we define the official providers that you can use for your own hints.
IDE may implement some of these or none of them. Also, it could eventually provide its However, your favorite IDE may implement some of these or none of them.
own. Also, it could eventually provide its own.
NOTE: As this is a new feature, IDE vendors must catch up with how it works. Adoption NOTE: As this is a new feature, IDE vendors must catch up with how it works.
times naturally vary. Adoption times naturally vary.
The following table summarizes the list of supported providers: The following table summarizes the list of supported providers:
[cols="2,4"] [cols="2,4"]
|=== |===
|Name | Description | Name | Description
|`any` | `any`
|Permits any additional value to be provided. | Permits any additional value to be provided.
|`class-reference` | `class-reference`
|Auto-completes the classes available in the project. Usually constrained by a base | Auto-completes the classes available in the project.
class that is specified by the `target` parameter. Usually constrained by a base class that is specified by the `target` parameter.
|`handle-as` | `handle-as`
|Handles the property as if it were defined by the type defined by the mandatory `target` | Handles the property as if it were defined by the type defined by the mandatory `target` parameter.
parameter.
|`logger-name` | `logger-name`
|Auto-completes valid logger names and | Auto-completes valid logger names and <<spring-boot-features.adoc#boot-features-custom-log-groups,logger groups>>.
<<spring-boot-features.adoc#boot-features-custom-log-groups,logger groups>>. Typically, Typically, package and class names available in the current project can be auto-completed as well as defined groups.
package and class names available in the current project can be auto-completed as well as
defined groups.
|`spring-bean-reference` | `spring-bean-reference`
|Auto-completes the available bean names in the current project. Usually constrained | Auto-completes the available bean names in the current project.
by a base class that is specified by the `target` parameter. 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.
| `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 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_.
providers if they can all manage the property _in some way_. Make sure to place the most 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.
powerful provider first, as the IDE must use the first one in the JSON section that it If no provider for a given property is supported, no special content assistance is provided, either.
can handle. If no provider for a given property is supported, no special content
assistance is provided, either.
===== Any ===== Any
The special **any** provider value permits any additional values to be provided. Regular The special **any** provider value permits any additional values to be provided.
value validation based on the property type should be applied if this is supported. 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 This provider is typically used if you have a list of values and any extra values should still be considered as valid.
should still be considered as valid.
The following example offers `on` and `off` as auto-completion values for `system.state`: The following example offers `on` and `off` as auto-completion values for `system.state`:
...@@ -495,29 +449,28 @@ The following example offers `on` and `off` as auto-completion values for `syste ...@@ -495,29 +449,28 @@ The following example offers `on` and `off` as auto-completion values for `syste
Note that, in the preceding example, any other value is also allowed. Note that, in the preceding example, any other value is also allowed.
===== Class Reference ===== Class Reference
The **class-reference** provider auto-completes classes available in the project. This The **class-reference** provider auto-completes classes available in the project.
provider supports the following parameters: This provider supports the following parameters:
[cols="1,1,2,4"] [cols="1,1,2,4"]
|=== |===
|Parameter |Type |Default value |Description | Parameter | Type | Default value | Description
|`target` | `target`
|`String` (`Class`) | `String` (`Class`)
|_none_ | _none_
|The fully qualified name of the class that should be assignable to the chosen value. | 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 Typically used to filter out-non candidate classes.
be provided by the type itself by exposing a class with the appropriate upper bound. Note that this information can be provided by the type itself by exposing a class with the appropriate upper bound.
|`concrete` | `concrete`
|`boolean` | `boolean`
|true | true
|Specify whether only concrete classes are to be considered as valid candidates. | 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` The following metadata snippet corresponds to the standard `server.servlet.jsp.class-name` property that defines the `JspServlet` class name to use:
property that defines the `JspServlet` class name to use:
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -539,43 +492,34 @@ property that defines the `JspServlet` class name to use: ...@@ -539,43 +492,34 @@ property that defines the `JspServlet` class name to use:
===== Handle As ===== Handle As
The **handle-as** provider lets you substitute the type of the property to a more The **handle-as** provider lets you substitute the type of the property to a more high-level type.
high-level type. This typically happens when the property has a `java.lang.String` 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.
because you do not want your configuration classes to rely on classes that may not be This provider supports the following parameters:
on the classpath. This provider supports the following parameters:
[cols="1,1,2,4"] [cols="1,1,2,4"]
|=== |===
|Parameter |Type |Default value |Description | Parameter | Type | Default value | Description
| **`target`** | **`target`**
| `String` (`Class`) | `String` (`Class`)
|_none_ | _none_
|The fully qualified name of the type to consider for the property. This parameter is | The fully qualified name of the type to consider for the property.
mandatory. This parameter is mandatory.
|=== |===
The following types can be used: The following types can be used:
* Any `java.lang.Enum`: Lists the possible values for the property. (We recommend * Any `java.lang.Enum`: Lists the possible values for the property.
defining the property with the `Enum` type, as no further hint should be required for (We recommend defining the property with the `Enum` type, as no further hint should be required for the IDE to auto-complete the values)
the IDE to auto-complete the values.) * `java.nio.charset.Charset`: Supports auto-completion of charset/encoding values (such as `UTF-8`)
* `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`) * `java.util.Locale`: auto-completion of locales (such as `en_US`)
* `org.springframework.util.MimeType`: Supports auto-completion of content type values * `org.springframework.util.MimeType`: Supports auto-completion of content type values (such as `text/plain`)
(such as `text/plain`) * `org.springframework.core.io.Resource`: Supports auto-completion of Spring’s Resource abstraction to refer to a file on the filesystem or on the classpath (such as `classpath:/sample.properties`)
* `org.springframework.core.io.Resource`: Supports auto-completion of Spring’s 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 TIP: If multiple values can be provided, use a `Collection` or _Array_ type to teach the IDE about it.
IDE about it.
The following metadata snippet corresponds to the standard `spring.liquibase.change-log` The following metadata snippet corresponds to the standard `spring.liquibase.change-log` property that defines the path to the changelog to use.
property that defines the path to the changelog to use. It is actually used internally as a 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.
`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] [source,json,indent=0]
---- ----
...@@ -597,33 +541,28 @@ keep the original String value to pass it to the Liquibase API. ...@@ -597,33 +541,28 @@ keep the original String value to pass it to the Liquibase API.
===== Logger Name ===== Logger Name
The **logger-name** provider auto-completes valid logger names and The **logger-name** provider auto-completes valid logger names and <<spring-boot-features.adoc#boot-features-custom-log-groups,logger groups>>.
<<spring-boot-features.adoc#boot-features-custom-log-groups,logger groups>>. Typically, Typically, package and class names available in the current project can be auto-completed.
package and class names available in the current project can be auto-completed. If groups If groups are enabled (default) and if a custom logger group is identified in the configuration, auto-completion for it should be provided.
are enabled (default) and if a custom logger group is identified in the configuration, Specific frameworks may have extra magic logger names that can be supported as well.
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: This provider supports the following parameters:
[cols="1,1,2,4"] [cols="1,1,2,4"]
|=== |===
|Parameter |Type |Default value |Description | Parameter | Type | Default value | Description
|`group` | `group`
|`boolean` | `boolean`
|`true` | `true`
|Specify whether known groups should be considered. | Specify whether known groups should be considered.
|=== |===
Since a logger name can be any arbitrary name, this provider should allow any 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.
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 The following metadata snippet corresponds to the standard `logging.level` property.
are _logger names_, and values correspond to the standard log levels or any custom Keys are _logger names_, and values correspond to the standard log levels or any custom level.
level. As Spring Boot defines a few logger groups out-of-the-box, dedicated value hints As Spring Boot defines a few logger groups out-of-the-box, dedicated value hints have been added for those.
have been added for those.
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -688,22 +627,21 @@ have been added for those. ...@@ -688,22 +627,21 @@ have been added for those.
===== Spring Bean Reference ===== Spring Bean Reference
The **spring-bean-reference** provider auto-completes the beans that are defined in The **spring-bean-reference** provider auto-completes the beans that are defined in the configuration of the current project.
the configuration of the current project. This provider supports the following parameters: This provider supports the following parameters:
[cols="1,1,2,4"] [cols="1,1,2,4"]
|=== |===
|Parameter |Type |Default value |Description | Parameter | Type | Default value | Description
|`target` | `target`
| `String` (`Class`) | `String` (`Class`)
|_none_ | _none_
|The fully qualified name of the bean class that should be assignable to the candidate. | The fully qualified name of the bean class that should be assignable to the candidate.
Typically used to filter out non-candidate beans. Typically used to filter out non-candidate beans.
|=== |===
The following metadata snippet corresponds to the standard `spring.jmx.server` property The following metadata snippet corresponds to the standard `spring.jmx.server` property that defines the name of the `MBeanServer` bean to use:
that defines the name of the `MBeanServer` bean to use:
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -722,17 +660,15 @@ that defines the name of the `MBeanServer` bean to use: ...@@ -722,17 +660,15 @@ that defines the name of the `MBeanServer` bean to use:
]} ]}
---- ----
NOTE: The binder is not aware of the metadata. If you provide that hint, you still need NOTE: The binder is not aware of the metadata.
to transform the bean name into an actual Bean reference using by the `ApplicationContext`. 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 ===== Spring Profile Name
The **spring-profile-name** provider auto-completes the Spring profiles that are The **spring-profile-name** provider auto-completes the Spring profiles that are defined in the configuration of the current project.
defined in the configuration of the current project.
The following metadata snippet corresponds to the standard `spring.profiles.active` The following metadata snippet corresponds to the standard `spring.profiles.active` property that defines the name of the Spring profile(s) to enable:
property that defines the name of the Spring profile(s) to enable:
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -752,14 +688,11 @@ property that defines the name of the Spring profile(s) to enable: ...@@ -752,14 +688,11 @@ property that defines the name of the Spring profile(s) to enable:
[[configuration-metadata-annotation-processor]] [[configuration-metadata-annotation-processor]]
=== Generating Your Own Metadata by Using the Annotation Processor === Generating Your Own Metadata by Using the Annotation Processor
You can easily generate your own configuration metadata file from items annotated with You can easily generate your own configuration metadata file from items annotated with `@ConfigurationProperties` by using the `spring-boot-configuration-processor` jar.
`@ConfigurationProperties` by using the `spring-boot-configuration-processor` jar. The jar includes a Java annotation processor which is invoked as your project is compiled.
The jar includes a Java annotation processor which is invoked as your project is To use the processor, include a dependency on `spring-boot-configuration-processor`.
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 With Maven the dependency should be declared as optional, as shown in the following example:
example:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -770,8 +703,7 @@ example: ...@@ -770,8 +703,7 @@ example:
</dependency> </dependency>
---- ----
With Gradle 4.5 and earlier, the dependency should be declared in the `compileOnly` With Gradle 4.5 and earlier, the dependency should be declared in the `compileOnly` configuration, as shown in the following example:
configuration, as shown in the following example:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"] [source,groovy,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -780,8 +712,7 @@ configuration, as shown in the following example: ...@@ -780,8 +712,7 @@ configuration, as shown in the following example:
} }
---- ----
With Gradle 4.6 and later, the dependency should be declared in the `annotationProcessor` With Gradle 4.6 and later, the dependency should be declared in the `annotationProcessor` configuration, as shown in the following example:
configuration, as shown in the following example:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"] [source,groovy,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -790,35 +721,26 @@ configuration, as shown in the following example: ...@@ -790,35 +721,26 @@ configuration, as shown in the following example:
} }
---- ----
If you are using an `additional-spring-configuration-metadata.json` file, the 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:
`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"] [source,groovy,indent=0,subs="verbatim,quotes,attributes"]
---- ----
compileJava.dependsOn(processResources) compileJava.dependsOn(processResources)
---- ----
This dependency ensures that the additional metadata is available when the annotation This dependency ensures that the additional metadata is available when the annotation processor runs during compilation.
processor runs during compilation.
The processor picks up both classes and methods that are annotated with The processor picks up both classes and methods that are annotated with `@ConfigurationProperties`.
`@ConfigurationProperties`. The Javadoc for field values within configuration classes The Javadoc for field values within configuration classes is used to populate the `description` attribute.
is used to populate the `description` attribute.
NOTE: You should only use simple text with `@ConfigurationProperties` field Javadoc, since NOTE: You should only use simple text with `@ConfigurationProperties` field Javadoc, since they are not processed before being added to the JSON.
they are not processed before being added to the JSON.
Properties are discovered through the presence of standard getters and setters with 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).
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 also supports the use of the `@Data`, `@Getter`, and `@Setter`
lombok annotations.
The annotation processor cannot auto-detect default values for ``Enum``s and The annotation processor cannot auto-detect default values for ``Enum``s and ``Collections``s.
``Collections``s. In the cases where a `Collection` or `Enum` property has a non-empty In the cases where a `Collection` or `Enum` property has a non-empty default value, <<configuration-metadata-additional-metadata,manual metadata>> should be provided.
default value, <<configuration-metadata-additional-metadata,manual metadata>> should be
provided.
Consider the following class: Consider the following class:
...@@ -836,7 +758,6 @@ Consider the following class: ...@@ -836,7 +758,6 @@ Consider the following class:
public enum ContainerType { public enum ContainerType {
SIMPLE, SIMPLE,
DIRECT DIRECT
} }
...@@ -844,9 +765,7 @@ Consider the following class: ...@@ -844,9 +765,7 @@ Consider the following class:
} }
---- ----
In order to document default values for properties in the class above, you could add the 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>>:
following content to <<configuration-metadata-additional-metadata,the manual metadata of
the module>>:
[source,json,indent=0] [source,json,indent=0]
---- ----
...@@ -862,18 +781,14 @@ the module>>: ...@@ -862,18 +781,14 @@ the module>>:
]} ]}
---- ----
Only the `name` of the property is required to document additional fields with manual Only the `name` of the property is required to document additional fields with manual metadata.
metadata.
[NOTE] [NOTE]
==== ====
If you are using AspectJ in your project, you need to make sure that the annotation If you are using AspectJ in your project, you need to make sure that the annotation processor runs only once.
processor runs only once. There are several ways to do this. With Maven, you can There are several ways to do this.
configure the `maven-apt-plugin` explicitly and add the dependency to the annotation With Maven, you can configure the `maven-apt-plugin` explicitly and add the dependency to the annotation processor only there.
processor only there. You could also let the AspectJ plugin run all the processing You could also let the AspectJ plugin run all the processing and disable annotation processing in the `maven-compiler-plugin` configuration, as follows:
and disable annotation processing in the `maven-compiler-plugin` configuration, as
follows:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -918,29 +833,22 @@ Consider the following class: ...@@ -918,29 +833,22 @@ Consider the following class:
} }
---- ----
The preceding example produces metadata information for `server.name`, `server.host.ip`, The preceding example produces metadata information for `server.name`, `server.host.ip`, and `server.host.port` properties.
and `server.host.port` properties. You can use the `@NestedConfigurationProperty` 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.
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.
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]] [[configuration-metadata-additional-metadata]]
==== Adding Additional Metadata ==== Adding Additional Metadata
Spring Boot's configuration file handling is quite flexible, and it is often the case 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.
that properties may exist that are not bound to a `@ConfigurationProperties` bean. You You may also need to tune some attributes of an existing key.
may also need to tune some attributes of an existing key. To support such cases and let 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.
you provide custom "hints", the annotation processor automatically merges items
from `META-INF/additional-spring-configuration-metadata.json` into the main metadata If you refer to a property that has been detected automatically, the description, default value, and deprecation information are overridden, if specified.
file. If the manual property declaration is not identified in the current module, it is added as a new property.
If you refer to a property that has been detected automatically, the description, The format of the `additional-spring-configuration-metadata.json` file is exactly the same as the regular `spring-configuration-metadata.json`.
default value, and deprecation information are overridden, if specified. If the manual The additional properties file is optional.
property declaration is not identified in the current module, it is added as a new If you do not have any additional properties, do not add the file.
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.
[appendix] [appendix]
[[appendix-dependency-versions]] [[appendix-dependency-versions]]
== Dependency versions == Dependency versions
The following table provides details of all of the dependency versions that are provided 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.
by Spring Boot in its CLI (Command Line Interface), Maven dependency management, and When you declare a dependency on one of these artifacts without declaring a version, the version listed in the table is used.
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::../../../target/generated-resources/effective-pom.adoc[] include::../../../target/generated-resources/effective-pom.adoc[]
[appendix] [appendix]
[[executable-jar]] [[executable-jar]]
== The Executable Jar Format == The Executable Jar Format
The `spring-boot-loader` modules lets Spring Boot support executable jar and The `spring-boot-loader` modules lets Spring Boot support executable jar and war files.
war files. If you use the Maven plugin or the Gradle plugin, executable jars are 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.
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 If you need to create executable jars from a different build system or if you are just curious about the underlying technology, this section provides some background.
curious about the underlying technology, this section provides some background.
[[executable-jar-nested-jars]] [[executable-jar-nested-jars]]
=== Nested JARs === Nested JARs
Java does not provide any standard way to load nested jar files (that is, jar files that Java does not provide any standard way to load nested jar files (that is, jar files that are themselves contained within a jar).
are themselves contained within a jar). This can be problematic if you need This can be problematic if you need to distribute a self-contained application that can be run from the command line without unpacking.
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 To solve this problem, many developers use "`shaded`" jars.
all classes, from all jars, into a single "`uber jar`". The problem with shaded jars is A shaded jar packages all classes, from all jars, into a single "`uber jar`".
that it becomes hard to see which libraries are actually in your application. 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) It can also be problematic if the same filename is used (but with different content) in multiple jars.
in multiple jars. Spring Boot takes a different approach and lets you actually nest Spring Boot takes a different approach and lets you actually nest jars directly.
jars directly.
...@@ -86,19 +80,16 @@ Spring Boot Loader-compatible war files should be structured in the following wa ...@@ -86,19 +80,16 @@ Spring Boot Loader-compatible war files should be structured in the following wa
+-dependency3.jar +-dependency3.jar
---- ----
Dependencies should be placed in a nested `WEB-INF/lib` directory. Any dependencies Dependencies should be placed in a nested `WEB-INF/lib` directory.
that are required when running embedded but are not required when deploying to 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`.
a traditional web container should be placed in `WEB-INF/lib-provided`.
[[executable-jar-jarfile]] [[executable-jar-jarfile]]
=== Spring Boot's "`JarFile`" Class === Spring Boot's "`JarFile`" Class
The core class used to support loading nested jars is The core class used to support loading nested jars is `org.springframework.boot.loader.jar.JarFile`.
`org.springframework.boot.loader.jar.JarFile`. It lets you load jar It lets you load jar content from a standard jar file or from nested child jar data.
content from a standard jar file or from nested child jar data. When first loaded, the 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:
location of each `JarEntry` is mapped to a physical file offset of the outer jar, as
shown in the following example:
[indent=0] [indent=0]
---- ----
...@@ -113,52 +104,41 @@ shown in the following example: ...@@ -113,52 +104,41 @@ shown in the following example:
0063 3452 3980 0063 3452 3980
---- ----
The preceding example shows how `A.class` can be found in `/BOOT-INF/classes` in The preceding example shows how `A.class` can be found in `/BOOT-INF/classes` in `myapp.jar` at position `0063`.
`myapp.jar` at position `0063`. `B.class` from the nested jar can actually be found in `B.class` from the nested jar can actually be found in `myapp.jar` at position `3452`, and `C.class` is at position `3980`.
`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 Armed with this information, we can load specific nested entries by seeking to the appropriate part of the outer jar.
the appropriate part of the outer jar. We do not need to unpack the archive, and we We do not need to unpack the archive, and we do not need to read all entry data into memory.
do not need to read all entry data into memory.
[[executable-jar-jarfile-compatibility]] [[executable-jar-jarfile-compatibility]]
==== Compatibility with the Standard Java "`JarFile`" ==== Compatibility with the Standard Java "`JarFile`"
Spring Boot Loader strives to remain compatible with existing code and libraries. 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 `org.springframework.boot.loader.jar.JarFile` extends from `java.util.jar.JarFile` and should work as a drop-in replacement.
should work as a drop-in replacement. The `getURL()` method returns a `URL` that The `getURL()` method returns a `URL` that opens a connection compatible with `java.net.JarURLConnection` and can be used with Java's `URLClassLoader`.
opens a connection compatible with `java.net.JarURLConnection` and can be used with Java's
`URLClassLoader`.
[[executable-jar-launching]] [[executable-jar-launching]]
=== Launching Executable Jars === Launching Executable Jars
The `org.springframework.boot.loader.Launcher` class is a special bootstrap class that The `org.springframework.boot.loader.Launcher` class is a special bootstrap class that is used as an executable jar's main entry point.
is used as an executable jar's main entry point. It is the actual `Main-Class` in your jar 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.
file, and it is used to setup an appropriate `URLClassLoader` and ultimately call your
`main()` method.
There are three launcher subclasses (`JarLauncher`, `WarLauncher`, and There are three launcher subclasses (`JarLauncher`, `WarLauncher`, and `PropertiesLauncher`).
`PropertiesLauncher`). Their purpose is to load resources (`.class` files and so on.) from 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).
nested jar files or war files in directories (as opposed to those explicitly on the In the case of `JarLauncher` and `WarLauncher`, the nested paths are fixed.
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/`.
`JarLauncher` looks in `BOOT-INF/lib/`, and `WarLauncher` looks in `WEB-INF/lib/` and You can add extra jars in those locations if you want more.
`WEB-INF/lib-provided/`. You can add extra jars in those locations if you want more. The The `PropertiesLauncher` looks in `BOOT-INF/lib/` in your application archive by default.
`PropertiesLauncher` looks in `BOOT-INF/lib/` in your application archive by default, but 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).
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]] [[executable-jar-launcher-manifest]]
==== Launcher Manifest ==== Launcher Manifest
You need to specify an appropriate `Launcher` as the `Main-Class` attribute of You need to specify an appropriate `Launcher` as the `Main-Class` attribute of `META-INF/MANIFEST.MF`.
`META-INF/MANIFEST.MF`. The actual class that you want to launch (that is, the class that 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.
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: The following example shows a typical `MANIFEST.MF` for an executable jar file:
...@@ -176,16 +156,16 @@ For a war file, it would be as follows: ...@@ -176,16 +156,16 @@ For a war file, it would be as follows:
Start-Class: com.mycompany.project.MyApplication Start-Class: com.mycompany.project.MyApplication
---- ----
NOTE: You need not specify `Class-Path` entries in your manifest file. The classpath NOTE: You need not specify `Class-Path` entries in your manifest file.
is deduced from the nested jars. The classpath is deduced from the nested jars.
[[executable-jar-exploded-archives]] [[executable-jar-exploded-archives]]
==== Exploded Archives ==== Exploded Archives
Certain PaaS implementations may choose to unpack archives before they run. For example, Certain PaaS implementations may choose to unpack archives before they run.
Cloud Foundry operates this way. You can run an unpacked archive by starting For example, Cloud Foundry operates this way.
the appropriate launcher, as follows: You can run an unpacked archive by starting the appropriate launcher, as follows:
[indent=0] [indent=0]
---- ----
...@@ -197,136 +177,114 @@ the appropriate launcher, as follows: ...@@ -197,136 +177,114 @@ the appropriate launcher, as follows:
[[executable-jar-property-launcher-features]] [[executable-jar-property-launcher-features]]
=== `PropertiesLauncher` 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`).
`PropertiesLauncher` has a few special features that can be enabled with external The following table describes these properties:
properties (System properties, environment variables, manifest entries, or
`loader.properties`). The following table describes these properties:
|=== |===
|Key |Purpose | Key | Purpose
|`loader.path` | `loader.path`
|Comma-separated Classpath, such as `lib,$\{HOME}/app/lib`. Earlier entries take | Comma-separated Classpath, such as `lib,$\{HOME}/app/lib`.
precedence, like a regular `-classpath` on the `javac` command line. Earlier entries take precedence, like a regular `-classpath` on the `javac` command line.
|`loader.home` | `loader.home`
|Used to resolve relative paths in `loader.path`. For example, given `loader.path=lib`, | Used to resolve relative paths in `loader.path`.
then `${loader.home}/lib` is a classpath location (along with all jar files in that For example, given `loader.path=lib`, then `${loader.home}/lib` is a classpath location (along with all jar files in that directory).
directory). This property is also used to locate a `loader.properties` file, as in the This property is also used to locate a `loader.properties` file, as in the following example `file:///opt/app` It defaults to `${user.dir}`.
following example `file:///opt/app`
It defaults to `${user.dir}`.
|`loader.args` | `loader.args`
|Default arguments for the main method (space separated). | Default arguments for the main method (space separated).
|`loader.main` | `loader.main`
|Name of main class to launch (for example, `com.app.Application`). | Name of main class to launch (for example, `com.app.Application`).
|`loader.config.name` | `loader.config.name`
|Name of properties file (for example, `launcher`) It defaults to `loader`. | Name of properties file (for example, `launcher`).
It defaults to `loader`.
|`loader.config.location` | `loader.config.location`
|Path to properties file (for example, `classpath:loader.properties`). It defaults to | Path to properties file (for example, `classpath:loader.properties`).
`loader.properties`. It defaults to `loader.properties`.
|`loader.system` | `loader.system`
|Boolean flag to indicate that all properties should be added to System properties | Boolean flag to indicate that all properties should be added to System properties.
It defaults to `false`. It defaults to `false`.
|=== |===
When specified as environment variables or manifest entries, the following names should When specified as environment variables or manifest entries, the following names should be used:
be used:
|=== |===
|Key | Manifest entry | Environment variable | Key | Manifest entry | Environment variable
|`loader.path`
|`Loader-Path`
|`LOADER_PATH`
|`loader.home` | `loader.path`
|`Loader-Home` | `Loader-Path`
|`LOADER_HOME` | `LOADER_PATH`
|`loader.args` | `loader.home`
|`Loader-Args` | `Loader-Home`
|`LOADER_ARGS` | `LOADER_HOME`
|`loader.main` | `loader.args`
|`Start-Class` | `Loader-Args`
|`LOADER_MAIN` | `LOADER_ARGS`
|`loader.config.location` | `loader.main`
|`Loader-Config-Location` | `Start-Class`
|`LOADER_CONFIG_LOCATION` | `LOADER_MAIN`
|`loader.system` | `loader.config.location`
|`Loader-System` | `Loader-Config-Location`
|`LOADER_SYSTEM` | `LOADER_CONFIG_LOCATION`
| `loader.system`
| `Loader-System`
| `LOADER_SYSTEM`
|=== |===
TIP: Build plugins automatically move the `Main-Class` attribute to `Start-Class` when TIP: Build plugins automatically move the `Main-Class` attribute to `Start-Class` when the fat jar is built.
the fat jar is built. If you use that, specify the name of the class to launch by using If you use that, specify the name of the class to launch by using the `Main-Class` attribute and leaving out `Start-Class`.
the `Main-Class` attribute and leaving out `Start-Class`.
The following rules apply to working with `PropertiesLauncher`: The following rules apply to working with `PropertiesLauncher`:
* `loader.properties` is searched for in `loader.home`, then in the root of the * `loader.properties` is searched for in `loader.home`, then in the root of the classpath, and then in `classpath:/BOOT-INF/classes`.
classpath, and then in `classpath:/BOOT-INF/classes`. The first location where a file The first location where a file with that name exists is used.
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.home` is the directory location of an additional properties file * `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).
(overriding the default) only when `loader.config.location` is not specified. Archive paths can be relative to `loader.home` or anywhere in the file system with a `jar:file:` prefix.
* `loader.path` can contain directories (which are scanned recursively for jar and zip * `loader.path` (if empty) defaults to `BOOT-INF/lib` (meaning a local directory or a nested one if running from an archive).
files), archive paths, a directory within an archive that is scanned for jar files (for Because of this, `PropertiesLauncher` behaves the same as `JarLauncher` when no additional configuration is provided.
example, `dependencies.jar!/lib`), or wildcard patterns (for the default JVM behavior). * `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).
Archive paths can be relative to `loader.home` or anywhere in the file system with a * Placeholder replacement is done from System and environment variables plus the properties file itself on all values before use.
`jar:file:` prefix. * 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.
* `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]]
=== Executable Jar Restrictions === Executable Jar Restrictions
You need to consider the following restrictions when working with a Spring You need to consider the following restrictions when working with a Spring Boot Loader packaged application:
Boot Loader packaged application:
[[executable-jar-zip-entry-compression]] [[executable-jar-zip-entry-compression]]
* Zip entry compression: * Zip entry compression:
The `ZipEntry` for a nested jar must be saved by using the `ZipEntry.STORED` method. This The `ZipEntry` for a nested jar must be saved by using the `ZipEntry.STORED` method.
is required so that we can seek directly to individual content within the nested jar. 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 The content of the nested jar file itself can still be compressed, as can any other entries in the outer jar.
entries in the outer jar.
[[executable-jar-system-classloader]] [[executable-jar-system-classloader]]
* System classLoader: * System classLoader:
Launched applications should use `Thread.getContextClassLoader()` when loading classes Launched applications should use `Thread.getContextClassLoader()` when loading classes (most libraries and frameworks do so by default).
(most libraries and frameworks do so by default). Trying to load nested jar Trying to load nested jar classes with `ClassLoader.getSystemClassLoader()` fails.
classes with `ClassLoader.getSystemClassLoader()` fails. `java.util.Logging` always uses the system classloader.
`java.util.Logging` always uses the system classloader. For this reason, you should For this reason, you should consider a different logging implementation.
consider a different logging implementation.
[[executable-jar-alternatives]] [[executable-jar-alternatives]]
=== Alternative Single Jar Solutions === Alternative Single Jar Solutions
If the preceding restrictions mean that you cannot use Spring Boot Loader, consider the If the preceding restrictions mean that you cannot use Spring Boot Loader, consider the following alternatives:
following alternatives:
* https://maven.apache.org/plugins/maven-shade-plugin/[Maven Shade Plugin] * https://maven.apache.org/plugins/maven-shade-plugin/[Maven Shade Plugin]
* http://www.jdotsoft.com/JarClassLoader.php[JarClassLoader] * http://www.jdotsoft.com/JarClassLoader.php[JarClassLoader]
......
[appendix] [appendix]
[[test-auto-configuration]] [[test-auto-configuration]]
== Test auto-configuration annotations == Test auto-configuration annotations
The following table lists the various `@…Test` annotations that can be used to test 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:
slices of your application and the auto-configuration that they import by default:
include::../../../target/generated-resources/test-slice-auto-configuration.adoc[] include::../../../target/generated-resources/test-slice-auto-configuration.adoc[]
...@@ -3,31 +3,25 @@ ...@@ -3,31 +3,25 @@
[partintro] [partintro]
-- --
Spring Boot provides build tool plugins for Maven and Gradle. The plugins offer a variety Spring Boot provides build tool plugins for Maven and Gradle. The plugins offer a variety of features, including the packaging of executable jars.
of features, including the packaging of executable jars. This section provides more This section provides more details on both plugins as well as some help should you need to extend an unsupported build system.
details on both plugins as well as some help should you need to extend an unsupported 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 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]] [[build-tool-plugins-maven-plugin]]
== Spring Boot Maven Plugin == Spring Boot Maven Plugin
The {spring-boot-maven-plugin-site}[Spring Boot Maven Plugin] provides Spring Boot The {spring-boot-maven-plugin-site}[Spring Boot Maven Plugin] provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application "`in-place`".
support in Maven, letting you package executable jar or war archives and run an To use it, you must use Maven 3.2 (or later).
application "`in-place`". To use it, you must use Maven 3.2 (or later).
NOTE: See the {spring-boot-maven-plugin-site}[Spring Boot Maven Plugin Site] for complete NOTE: See the {spring-boot-maven-plugin-site}[Spring Boot Maven Plugin Site] for complete plugin documentation.
plugin documentation.
[[build-tool-plugins-include-maven-plugin]] [[build-tool-plugins-include-maven-plugin]]
=== Including the Plugin === Including the Plugin
To use the Spring Boot Maven Plugin, include the appropriate XML in the `plugins` 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:
section of your `pom.xml`, as shown in the following example:
[source,xml,indent=0,subs="verbatim,attributes"] [source,xml,indent=0,subs="verbatim,attributes"]
---- ----
...@@ -55,9 +49,8 @@ section of your `pom.xml`, as shown in the following example: ...@@ -55,9 +49,8 @@ section of your `pom.xml`, as shown in the following example:
</project> </project>
---- ----
The preceding configuration repackages a jar or war that is built during the `package` The preceding configuration repackages a jar or war that is built during the `package` phase of the Maven lifecycle.
phase of the Maven lifecycle. The following example shows both the repackaged jar as well The following example shows both the repackaged jar as well as the original jar in the `target` directory:
as the original jar in the `target` directory:
[indent=0] [indent=0]
---- ----
...@@ -67,9 +60,7 @@ as the original jar in the `target` directory: ...@@ -67,9 +60,7 @@ as the original jar in the `target` directory:
---- ----
If you do not include the `<execution/>` configuration, as shown in the prior example, you 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:
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] [indent=0]
---- ----
...@@ -78,8 +69,7 @@ the following example: ...@@ -78,8 +69,7 @@ the following example:
target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original 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 If you use a milestone or snapshot release, you also need to add the appropriate `pluginRepository` elements, as shown in the following listing:
`pluginRepository` elements, as shown in the following listing:
[source,xml,indent=0,subs="verbatim,attributes"] [source,xml,indent=0,subs="verbatim,attributes"]
---- ----
...@@ -99,10 +89,8 @@ If you use a milestone or snapshot release, you also need to add the appropriate ...@@ -99,10 +89,8 @@ If you use a milestone or snapshot release, you also need to add the appropriate
[[build-tool-plugins-maven-packaging]] [[build-tool-plugins-maven-packaging]]
=== Packaging Executable Jar and War Files === Packaging Executable Jar and War Files
Once `spring-boot-maven-plugin` has been included in your `pom.xml`, it automatically 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.
tries to rewrite archives to make them executable by using the `spring-boot:repackage` 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:
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"] [source,xml,indent=0,subs="verbatim,attributes"]
---- ----
...@@ -115,11 +103,10 @@ the usual `packaging` element, as shown in the following example: ...@@ -115,11 +103,10 @@ the usual `packaging` element, as shown in the following example:
</project> </project>
---- ----
Your existing archive is enhanced by Spring Boot during the `package` phase. The main Your existing archive is enhanced by Spring Boot during the `package` phase.
class that you want to launch can be specified either by using a configuration option, as 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.
shown below, or by adding a `Main-Class` attribute to the manifest. If you do not specify If you do not specify a main class, the plugin searches for a class with a `public static void main(String[] args)` method.
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"] [source,xml,indent=0,subs="verbatim,attributes"]
---- ----
<plugin> <plugin>
...@@ -140,9 +127,7 @@ To build and run a project artifact, you can type the following: ...@@ -140,9 +127,7 @@ To build and run a project artifact, you can type the following:
$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar $ 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 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:
need to mark the embedded container dependencies as "`provided`", as shown in the
following example:
[source,xml,indent=0,subs="verbatim,attributes"] [source,xml,indent=0,subs="verbatim,attributes"]
---- ----
...@@ -167,32 +152,28 @@ following example: ...@@ -167,32 +152,28 @@ following example:
</project> </project>
---- ----
TIP: See the "`<<howto-create-a-deployable-war-file>>`" section for more details on how to TIP: See the "`<<howto-create-a-deployable-war-file>>`" section for more details on how to create a deployable war file.
create a deployable war file.
Advanced configuration options and examples are available in the Advanced configuration options and examples are available in the {spring-boot-maven-plugin-site}[plugin info page].
{spring-boot-maven-plugin-site}[plugin info page].
[[build-tool-plugins-gradle-plugin]] [[build-tool-plugins-gradle-plugin]]
== Spring Boot Gradle Plugin == Spring Boot Gradle Plugin
The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, letting you package 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`.
executable jar or war archives, run Spring Boot applications, and use the dependency It requires Gradle 4.4 or later.
management provided by `spring-boot-dependencies`. It requires Gradle 4.4 or later. Please Please refer to the plugin's documentation to learn more:
refer to the plugin's documentation to learn more:
* Reference ({spring-boot-gradle-plugin}/reference/html[HTML] and * Reference ({spring-boot-gradle-plugin}/reference/html[HTML] and {spring-boot-gradle-plugin}/reference/pdf/spring-boot-gradle-plugin-reference.pdf[PDF])
{spring-boot-gradle-plugin}/reference/pdf/spring-boot-gradle-plugin-reference.pdf[PDF])
* {spring-boot-gradle-plugin}/api[API] * {spring-boot-gradle-plugin}/api[API]
[[build-tool-plugins-antlib]] [[build-tool-plugins-antlib]]
== Spring Boot AntLib Module == Spring Boot AntLib Module
The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant. You can The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant.
use the module to create executable jars. To use the module, you need to declare an You can use the module to create executable jars.
additional `spring-boot` namespace in your `build.xml`, as shown in the following example: 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] [source,xml,indent=0]
---- ----
...@@ -203,68 +184,66 @@ additional `spring-boot` namespace in your `build.xml`, as shown in the followin ...@@ -203,68 +184,66 @@ additional `spring-boot` namespace in your `build.xml`, as shown in the followin
</project> </project>
---- ----
You need to remember to start Ant using the `-lib` option, as shown in the following You need to remember to start Ant using the `-lib` option, as shown in the following example:
example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ ant -lib <folder containing spring-boot-antlib-{spring-boot-version}.jar> $ ant -lib <folder containing spring-boot-antlib-{spring-boot-version}.jar>
---- ----
TIP: The "`Using Spring Boot`" section includes a more complete example of 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`>>.
<<using-spring-boot.adoc#using-boot-ant, using Apache Ant with `spring-boot-antlib`>>.
[[spring-boot-ant-tasks]]
=== Spring Boot Ant Tasks === Spring Boot Ant Tasks
Once the `spring-boot-antlib` namespace has been declared, the following additional tasks Once the `spring-boot-antlib` namespace has been declared, the following additional tasks are available:
are available:
* <<spring-boot-ant-exejar>> * <<spring-boot-ant-exejar>>
* <<spring-boot-ant-findmainclass>> * <<spring-boot-ant-findmainclass>>
[[spring-boot-ant-exejar]] [[spring-boot-ant-exejar]]
==== `spring-boot:exejar` ==== `spring-boot:exejar`
You can use the `exejar` task to create a Spring Boot executable jar. The following You can use the `exejar` task to create a Spring Boot executable jar.
attributes are supported by the task: The following attributes are supported by the task:
[cols="1,2,2"] [cols="1,2,2"]
|==== |====
|Attribute |Description |Required | Attribute | Description | Required
|`destfile` | `destfile`
|The destination jar file to create | The destination jar file to create
|Yes | Yes
|`classes` | `classes`
|The root directory of Java class files | The root directory of Java class files
|Yes | Yes
|`start-class` | `start-class`
|The main application class to run | The main application class to run
|No _(the default is the first class found that declares a `main` method)_ | No _(the default is the first class found that declares a `main` method)_
|==== |====
The following nested elements can be used with the task: The following nested elements can be used with the task:
[cols="1,4"] [cols="1,4"]
|==== |====
|Element |Description | Element | Description
|`resources` | `resources`
|One or more {ant-manual}/Types/resources.html#collection[Resource Collections] describing | One or more {ant-manual}/Types/resources.html#collection[Resource Collections] describing a set of {ant-manual}/Types/resources.html[Resources] that should be added to the content of the created +jar+ file.
a set of {ant-manual}/Types/resources.html[Resources] that should be added to the content
of the created +jar+ file.
|`lib` | `lib`
|One or more {ant-manual}/Types/resources.html#collection[Resource Collections] that | One or more {ant-manual}/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.
should be added to the set of jar libraries that make up the runtime dependency classpath
of the application.
|==== |====
==== Examples
[[spring-boot-ant-exejar-examples]]
==== Examples
This section shows two examples of Ant tasks. This section shows two examples of Ant tasks.
.Specify +start-class+ .Specify +start-class+
...@@ -292,33 +271,34 @@ This section shows two examples of Ant tasks. ...@@ -292,33 +271,34 @@ This section shows two examples of Ant tasks.
---- ----
[[spring-boot-ant-findmainclass]] [[spring-boot-ant-findmainclass]]
=== `spring-boot:findmainclass` === `spring-boot:findmainclass`
The `findmainclass` task is used internally by `exejar` to locate a class declaring a The `findmainclass` task is used internally by `exejar` to locate a class declaring a `main`.
`main`. If necessary, you can also use this task directly in your build. The following If necessary, you can also use this task directly in your build.
attributes are supported: The following attributes are supported:
[cols="1,2,2"] [cols="1,2,2"]
|==== |====
|Attribute |Description |Required | Attribute | Description | Required
|`classesroot` | `classesroot`
|The root directory of Java class files | The root directory of Java class files
|Yes _(unless `mainclass` is specified)_ | Yes _(unless `mainclass` is specified)_
|`mainclass` | `mainclass`
|Can be used to short-circuit the `main` class search | Can be used to short-circuit the `main` class search
|No | No
|`property` | `property`
|The Ant property that should be set with the result | The Ant property that should be set with the result
|No _(result will be logged if unspecified)_ | No _(result will be logged if unspecified)_
|==== |====
[[spring-boot-ant-findmainclass-examples]]
==== Examples ==== Examples
This section contains three examples of using `findmainclass`. This section contains three examples of using `findmainclass`.
.Find and log .Find and log
...@@ -343,32 +323,27 @@ This section contains three examples of using `findmainclass`. ...@@ -343,32 +323,27 @@ This section contains three examples of using `findmainclass`.
[[build-tool-plugins-other-build-systems]] [[build-tool-plugins-other-build-systems]]
== Supporting 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 If you want to use a build tool other than Maven, Gradle, or Ant, you likely need to develop your own plugin.
develop your own plugin. Executable jars need to follow a specific format and certain 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).
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 The Spring Boot Maven and Gradle plugins both make use of `spring-boot-loader-tools` to actually generate jars.
actually generate jars. If you need to, you may use this library directly. If you need to, you may use this library directly.
[[build-tool-plugins-repackaging-archives]] [[build-tool-plugins-repackaging-archives]]
=== Repackaging Archives === Repackaging Archives
To repackage an existing archive so that it becomes a self-contained executable archive, To repackage an existing archive so that it becomes a self-contained executable archive, use `org.springframework.boot.loader.tools.Repackager`.
use `org.springframework.boot.loader.tools.Repackager`. The `Repackager` class takes a The `Repackager` class takes a single constructor argument that refers to an existing jar or war archive.
single constructor argument that refers to an existing jar or war archive. Use one of the Use one of the two available `repackage()` methods to either replace the original file or write to a new destination.
two available `repackage()` methods to either replace the original file or write to a new Various settings can also be configured on the repackager before it is run.
destination. Various settings can also be configured on the repackager before it is run.
[[build-tool-plugins-nested-libraries]] [[build-tool-plugins-nested-libraries]]
=== Nested Libraries === Nested Libraries
When repackaging an archive, you can include references to dependency files by using the When repackaging an archive, you can include references to dependency files by using the `org.springframework.boot.loader.tools.Libraries` interface.
`org.springframework.boot.loader.tools.Libraries` interface. We do not provide any We do not provide any concrete implementations of `Libraries` here as they are usually build-system-specific.
concrete implementations of `Libraries` here as they are usually build-system-specific.
If your archive already includes libraries, you can use `Libraries.NONE`. If your archive already includes libraries, you can use `Libraries.NONE`.
...@@ -376,10 +351,8 @@ If your archive already includes libraries, you can use `Libraries.NONE`. ...@@ -376,10 +351,8 @@ If your archive already includes libraries, you can use `Libraries.NONE`.
[[build-tool-plugins-find-a-main-class]] [[build-tool-plugins-find-a-main-class]]
=== Finding a Main Class === Finding a Main Class
If you do not use `Repackager.setMainClass()` to specify a main class, the repackager If you do not use `Repackager.setMainClass()` to specify a main class, the repackager uses https://asm.ow2.org/[ASM] to read class files and tries to find a suitable class with a `public static void main(String[] args)` method.
uses https://asm.ow2.org/[ASM] to read class files and tries to find a suitable class with An exception is thrown if more than one candidate is found.
a `public static void main(String[] args)` method. An exception is thrown if more than one
candidate is found.
...@@ -404,10 +377,7 @@ The following example shows a typical repackage implementation: ...@@ -404,10 +377,7 @@ The following example shows a typical repackage implementation:
[[build-tool-plugins-whats-next]] [[build-tool-plugins-whats-next]]
== What to Read Next == What to Read Next
If you are interested in how the build tool plugins work, you can If you are interested in how the build tool plugins work, you can look at the {github-code}/spring-boot-project/spring-boot-tools[`spring-boot-tools`] module on GitHub.
look at the {github-code}/spring-boot-project/spring-boot-tools[`spring-boot-tools`] More technical details of the executable jar format are covered in <<appendix-executable-jar-format.adoc#executable-jar,the appendix>>.
module on GitHub. More technical details of the executable jar format are covered in
<<appendix-executable-jar-format.adoc#executable-jar,the appendix>>.
If you have specific build-related questions, you can check out the If you have specific build-related questions, you can check out the "`<<howto.adoc#howto, how-to>>`" guides.
"`<<howto.adoc#howto, how-to>>`" guides.
...@@ -3,9 +3,8 @@ ...@@ -3,9 +3,8 @@
[partintro] [partintro]
-- --
Spring Boot's flexible packaging options provide a great deal of choice when it comes to Spring Boot's flexible packaging options provide a great deal of choice when it comes to deploying your application.
deploying your application. You can deploy Spring Boot applications to a variety You can deploy Spring Boot applications to a variety of cloud platforms, to container images (such as Docker), or to virtual/real machines.
of cloud platforms, to container images (such as Docker), or to virtual/real machines.
This section covers some of the more common deployment scenarios. This section covers some of the more common deployment scenarios.
-- --
...@@ -14,60 +13,44 @@ This section covers some of the more common deployment scenarios. ...@@ -14,60 +13,44 @@ This section covers some of the more common deployment scenarios.
[[cloud-deployment]] [[cloud-deployment]]
== Deploying to the Cloud == Deploying to the Cloud
Spring Boot's executable jars are ready-made for most popular cloud PaaS Spring Boot's executable jars are ready-made for most popular cloud PaaS (Platform-as-a-Service) providers.
(Platform-as-a-Service) providers. These providers tend to require that you These providers tend to require that you "`bring your own container`".
"`bring your own container`". They manage application processes (not Java applications 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.
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. 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. 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 It might be a JDK and a call to `java`, an embedded web server, or a full-fledged application server.
application server. A buildpack is pluggable, but ideally you should be able to get by A buildpack is pluggable, but ideally you should be able to get by with as few customizations to it as possible.
with as few customizations to it as possible. This reduces the footprint of functionality This reduces the footprint of functionality that is not under your control.
that is not under your control. It minimizes divergence between development and production It minimizes divergence between development and production environments.
environments.
Ideally, your application, like a Spring Boot executable jar, has everything that it needs Ideally, your application, like a Spring Boot executable jar, has everything that it needs to run packaged within it.
to run packaged within it.
In this section, we look at what it takes to get the 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.
<<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-deployment-cloud-foundry]]
=== Cloud Foundry === Cloud Foundry
Cloud Foundry provides default buildpacks that come into play if no other buildpack is Cloud Foundry provides default buildpacks that come into play if no other buildpack is specified.
specified. The Cloud Foundry https://github.com/cloudfoundry/java-buildpack[Java The Cloud Foundry https://github.com/cloudfoundry/java-buildpack[Java buildpack] has excellent support for Spring applications, including Spring Boot.
buildpack] has excellent support for Spring applications, including Spring Boot. You can You can deploy stand-alone executable jar applications as well as traditional `.war` packaged applications.
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.
Once you have built your application (by using, for example, `mvn clean package`) and have The following line shows using the `cf push` command to deploy an application:
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"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar $ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar
---- ----
NOTE: In the preceding example, we substitute `acloudyspringtime` for whatever value you NOTE: In the preceding example, we substitute `acloudyspringtime` for whatever value you give `cf` as the name of your application.
give `cf` as the name of your application.
See the https://docs.cloudfoundry.org/cf-cli/getting-started.html#push[`cf push` See the https://docs.cloudfoundry.org/cf-cli/getting-started.html#push[`cf push` documentation] for more options.
documentation] for more options. If there is a Cloud Foundry 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.
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 At this point, `cf` starts uploading your application, producing output similar to the following example:
following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -96,8 +79,7 @@ following example: ...@@ -96,8 +79,7 @@ following example:
Congratulations! The application is now live! Congratulations! The application is now live!
Once your application is live, you can verify the status of the deployed application by 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:
using the `cf apps` command, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -111,23 +93,18 @@ using the `cf apps` command, as shown in the following example: ...@@ -111,23 +93,18 @@ using the `cf apps` command, as shown in the following example:
... ...
---- ----
Once Cloud Foundry acknowledges that your application has been deployed, you should be Once Cloud Foundry acknowledges that your application has been deployed, you should be able to find the application at the URI given.
able to find the application at the URI given. In the preceding example, you could find In the preceding example, you could find it at `\https://acloudyspringtime.cfapps.io/`.
it at `\https://acloudyspringtime.cfapps.io/`.
[[cloud-deployment-cloud-foundry-services]] [[cloud-deployment-cloud-foundry-services]]
==== Binding to Services ==== Binding to Services
By default, metadata about the running application as well as service connection 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`).
information is exposed to the application as environment variables (for example: This architecture decision is due to Cloud Foundry's polyglot (any language and platform can be supported as a buildpack) nature.
`$VCAP_SERVICES`). This architecture decision is due to Cloud Foundry's polyglot (any Process-scoped environment variables are language agnostic.
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 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:
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] [source,java,indent=0]
---- ----
...@@ -146,40 +123,35 @@ extracts them and flattens the data into properties that can be accessed through ...@@ -146,40 +123,35 @@ extracts them and flattens the data into properties that can be accessed through
} }
---- ----
All Cloud Foundry properties are prefixed with `vcap`. You can use `vcap` properties to All Cloud Foundry properties are prefixed with `vcap`.
access application information (such as the public URL of the application) and service You can use `vcap` properties to access application information (such as the public URL of the application) and service information (such as database credentials).
information (such as database credentials). See the See the {dc-spring-boot}/cloud/CloudFoundryVcapEnvironmentPostProcessor.html['`CloudFoundryVcapEnvironmentPostProcessor`'] Javadoc for complete details.
{dc-spring-boot}/cloud/CloudFoundryVcapEnvironmentPostProcessor.html['`CloudFoundryVcapEnvironmentPostProcessor`']
Javadoc for complete details.
TIP: The https://cloud.spring.io/spring-cloud-connectors/[Spring Cloud Connectors] project TIP: The https://cloud.spring.io/spring-cloud-connectors/[Spring Cloud Connectors] project is a better fit for tasks such as configuring a DataSource.
is a better fit for tasks such as configuring a DataSource. Spring Boot includes Spring Boot includes auto-configuration support and a `spring-boot-starter-cloud-connectors` starter.
auto-configuration support and a `spring-boot-starter-cloud-connectors` starter.
[[cloud-deployment-heroku]] [[cloud-deployment-heroku]]
=== Heroku === Heroku
Heroku is another popular PaaS platform. To customize Heroku builds, you provide a Heroku is another popular PaaS platform.
`Procfile`, which provides the incantation required to deploy an application. Heroku To customize Heroku builds, you provide a `Procfile`, which provides the incantation required to deploy an application.
assigns a `port` for the Java application to use and then ensures that routing to the Heroku assigns a `port` for the Java application to use and then ensures that routing to the external URI works.
external URI works.
You must configure your application to listen on the correct port. The following example You must configure your application to listen on the correct port.
shows the `Procfile` for our starter REST application: The following example shows the `Procfile` for our starter REST application:
[indent=0] [indent=0]
---- ----
web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar 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 Spring Boot makes `-D` arguments available as properties accessible from a Spring `Environment` instance.
`Environment` instance. The `server.port` configuration property is fed to the embedded The `server.port` configuration property is fed to the embedded Tomcat, Jetty, or Undertow instance, which then uses the port when it starts up.
Tomcat, Jetty, or Undertow instance, which then uses the port when it starts up. The `$PORT` The `$PORT` environment variable is assigned to us by the Heroku PaaS.
environment variable is assigned to us by the Heroku PaaS.
This should be everything you need. The most common deployment workflow for Heroku This should be everything you need.
deployments is to `git push` the code to production, as shown in the following example: 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"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -224,17 +196,15 @@ deployments is to `git push` the code to production, as shown in the following e ...@@ -224,17 +196,15 @@ deployments is to `git push` the code to production, as shown in the following e
* [new branch] master -> master * [new branch] master -> master
---- ----
Your application should now be up and running on Heroku. For more details, refer to Your application should now be up and running on Heroku.
https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku[Deploying For more details, refer to https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku[Deploying Spring Boot Applications to Heroku].
Spring Boot Applications to Heroku].
[[cloud-deployment-openshift]] [[cloud-deployment-openshift]]
=== OpenShift === OpenShift
https://www.openshift.com/[OpenShift] is the Red Hat public (and enterprise) extension of https://www.openshift.com/[OpenShift] is the Red Hat public (and enterprise) extension of the Kubernetes container orchestration platform.
the Kubernetes container orchestration platform. Similarly to Kubernetes, OpenShift has Similarly to Kubernetes, OpenShift has many options for installing Spring Boot based applications.
many options for installing Spring Boot based applications.
OpenShift has many resources describing how to deploy Spring Boot applications, including: OpenShift has many resources describing how to deploy Spring Boot applications, including:
...@@ -244,11 +214,11 @@ OpenShift has many resources describing how to deploy Spring Boot applications, ...@@ -244,11 +214,11 @@ OpenShift has many resources describing how to deploy Spring Boot applications,
* https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/[OpenShift Commons Briefing] * https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/[OpenShift Commons Briefing]
[[cloud-deployment-aws]] [[cloud-deployment-aws]]
=== Amazon Web Services (AWS) === Amazon Web Services (AWS)
Amazon Web Services offers multiple ways to install Spring Boot-based applications, either 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.
as traditional web applications (war) or as executable jar files with an embedded web The options include:
server. The options include:
* AWS Elastic Beanstalk * AWS Elastic Beanstalk
* AWS Code Deploy * AWS Code Deploy
...@@ -256,30 +226,28 @@ server. The options include: ...@@ -256,30 +226,28 @@ server. The options include:
* AWS Cloud Formation * AWS Cloud Formation
* AWS Container Registry * AWS Container Registry
Each has different features and pricing models. In this document, we describe only the Each has different features and pricing models.
simplest option: AWS Elastic Beanstalk. In this document, we describe only the simplest option: AWS Elastic Beanstalk.
==== AWS Elastic Beanstalk ==== AWS Elastic Beanstalk
As described in the official 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.
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html[Elastic You can either use the "`Tomcat Platform`" or the "`Java SE platform`".
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 ===== Using the Tomcat Platform
This option applies to Spring Boot projects that produce a war file. No This option applies to Spring Boot projects that produce a war file.
special configuration is required. You need only follow the official guide. No special configuration is required.
You need only follow the official guide.
===== Using the Java SE Platform ===== Using the Java SE Platform
This option applies to Spring Boot projects that produce a jar file and run an embedded This option applies to Spring Boot projects that produce a jar file and run an embedded web container.
web container. Elastic Beanstalk environments run an nginx instance on port 80 to proxy Elastic Beanstalk environments run an nginx instance on port 80 to proxy the actual application, running on port 5000.
the actual application, running on port 5000. To configure it, add the following line to To configure it, add the following line to your `application.properties` file:
your `application.properties` file:
[indent=0] [indent=0]
---- ----
...@@ -290,11 +258,9 @@ your `application.properties` file: ...@@ -290,11 +258,9 @@ your `application.properties` file:
[TIP] [TIP]
.Upload binaries instead of sources .Upload binaries instead of sources
==== ====
By default, Elastic Beanstalk uploads sources and compiles them in AWS. However, it is By default, Elastic Beanstalk uploads sources and compiles them in AWS.
best to upload the binaries instead. To do so, add lines similar to the following to your However, it is best to upload the binaries instead.
`.elasticbeanstalk/config.yml` file: To do so, add lines similar to the following to your `.elasticbeanstalk/config.yml` file:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -306,12 +272,10 @@ best to upload the binaries instead. To do so, add lines similar to the followin ...@@ -306,12 +272,10 @@ best to upload the binaries instead. To do so, add lines similar to the followin
[TIP] [TIP]
.Reduce costs by setting the environment type .Reduce costs by setting the environment type
==== ====
By default an Elastic Beanstalk environment is load balanced. The load balancer has a By default an Elastic Beanstalk environment is load balanced.
significant cost. To avoid that cost, set the environment type to "`Single instance`", as The load balancer has a significant cost.
described in 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].
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity[the You can also create single instance environments by using the CLI and the following command:
Amazon documentation]. You can also create single instance environments by using the CLI
and the following command:
[indent=0] [indent=0]
---- ----
...@@ -320,45 +284,33 @@ and the following command: ...@@ -320,45 +284,33 @@ and the following command:
==== ====
==== Summary ==== Summary
This is one of the easiest ways to get to AWS, but there are more things to cover, such as 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.
how to integrate Elastic Beanstalk into any CI / CD tool, use the Elastic Beanstalk Maven There is a https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/[blog post] covering these topics more in detail.
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]] [[cloud-deployment-boxfuse]]
=== Boxfuse and Amazon Web Services === Boxfuse and Amazon Web Services
https://boxfuse.com/[Boxfuse] works by turning your Spring Boot executable jar or war 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.
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 comes with deep integration for Spring Boot and uses the information from your 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).
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 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:
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] [indent=0]
---- ----
$ boxfuse run myapp-1.0.jar -env=prod $ boxfuse run myapp-1.0.jar -env=prod
---- ----
See the https://boxfuse.com/docs/commandline/run.html[`boxfuse run` documentation] for See the https://boxfuse.com/docs/commandline/run.html[`boxfuse run` documentation] for more options.
more options. If there is a https://boxfuse.com/docs/commandline/#configuration[`boxfuse.conf`] file present in the current directory, it is considered. 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 TIP: By default, Boxfuse activates a Spring profile named `boxfuse` on startup.
executable jar or war contains an 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.
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 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:
and starts the necessary resources on AWS, resulting in output similar to the following
example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -383,32 +335,23 @@ example: ...@@ -383,32 +335,23 @@ example:
Your application should now be up and running on AWS. 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 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.
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]] [[cloud-deployment-gae]]
=== Google Cloud === Google Cloud
Google Cloud has several options that can be used to launch Spring Boot applications. 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 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.
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 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.
identifier for you and also sets up HTTP routes. Add a Java app to the project and leave Add a Java app to the project and leave it empty and then use the https://cloud.google.com/sdk/downloads[Google Cloud SDK] to push your Spring Boot app into that slot from the command line or CI build.
it empty and then use the https://cloud.google.com/sdk/downloads[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 App Engine Standard requires you to use WAR packaging.
https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/appengine-standard-java8/springboot-appengine-standard/README.md[these steps] 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.
to deploy App Engine Standard application to Google Cloud.
Alternatively, App Engine Flex requires you to create an `app.yaml` file to describe Alternatively, App Engine Flex requires you to create an `app.yaml` file to describe the resources your app requires.
the resources your app requires. Normally, you put this file in `src/main/appengine`, Normally, you put this file in `src/main/appengine`, and it should resemble the following file:
and it should resemble the following file:
[source,yaml,indent=0] [source,yaml,indent=0]
---- ----
...@@ -434,8 +377,7 @@ and it should resemble the following file: ...@@ -434,8 +377,7 @@ and it should resemble the following file:
ENCRYPT_KEY: your_encryption_key_here ENCRYPT_KEY: your_encryption_key_here
---- ----
You can deploy the app (for example, with a Maven plugin) by adding the project ID to the 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:
build configuration, as shown in the following example:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -449,25 +391,19 @@ build configuration, as shown in the following example: ...@@ -449,25 +391,19 @@ build configuration, as shown in the following example:
</plugin> </plugin>
---- ----
Then deploy with `mvn appengine:deploy` (if you need to authenticate first, the build Then deploy with `mvn appengine:deploy` (if you need to authenticate first, the build fails).
fails).
[[deployment-install]] [[deployment-install]]
== Installing Spring Boot Applications == Installing Spring Boot Applications
In addition to running Spring Boot applications by using `java -jar`, it is also In addition to running Spring Boot applications by using `java -jar`, it is also possible to make fully executable applications for Unix systems.
possible to make fully executable applications for Unix systems. A fully executable jar A fully executable jar can be executed like any other executable binary or it can be <<deployment-service,registered with `init.d` or `systemd`>>.
can be executed like any other executable binary or it can be This makes it very easy to install and manage Spring Boot applications in common production environments.
<<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. 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 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.
technique. For example, `jar -xf` may silently fail to extract a jar or war that has been 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.
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.
To create a '`fully executable`' jar with Maven, use the following plugin configuration: To create a '`fully executable`' jar with Maven, use the following plugin configuration:
...@@ -491,30 +427,28 @@ The following example shows the equivalent Gradle configuration: ...@@ -491,30 +427,28 @@ The following example shows the equivalent Gradle configuration:
} }
---- ----
You can then run your application by typing `./my-application.jar` (where `my-application` You can then run your application by typing `./my-application.jar` (where `my-application` is the name of your artifact).
is the name of your artifact). The directory containing the jar is used as your The directory containing the jar is used as your application's working directory.
application's working directory.
[[deployment-install-supported-operating-systems]] [[deployment-install-supported-operating-systems]]
=== Supported Operating Systems === Supported Operating Systems
The default script supports most Linux distributions and is tested on CentOS and Ubuntu. 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 Other platforms, such as OS X and FreeBSD, require the use of a custom `embeddedLaunchScript`.
`embeddedLaunchScript`.
[[deployment-service]] [[deployment-service]]
=== Unix/Linux Services === Unix/Linux Services
Spring Boot application can be easily started as Unix/Linux services by using either Spring Boot application can be easily started as Unix/Linux services by using either `init.d` or `systemd`.
`init.d` or `systemd`.
[[deployment-initd-service]] [[deployment-initd-service]]
==== Installation as an `init.d` Service (System V) ==== Installation as an `init.d` Service (System V)
If you configured Spring Boot's Maven or Gradle plugin to generate a <<deployment-install, 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.
fully executable jar>>, and you do not use a custom `embeddedLaunchScript`, your To do so, symlink the jar to `init.d` to support the standard `start`, `stop`, `restart`, and `status` commands.
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: The script supports the following features:
...@@ -522,27 +456,25 @@ The script supports the following features: ...@@ -522,27 +456,25 @@ The script supports the following features:
* Tracks the application's PID by using `/var/run/<appname>/<appname>.pid` * Tracks the application's PID by using `/var/run/<appname>/<appname>.pid`
* Writes console logs to `/var/log/<appname>.log` * Writes console logs to `/var/log/<appname>.log`
Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a 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:
Spring Boot application as an `init.d` service, create a symlink, as follows:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp $ 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 Once installed, you can start and stop the service in the usual way.
Debian-based system, you could start it with the following command: For example, on a Debian-based system, you could start it with the following command:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ service myapp start $ service myapp start
---- ----
TIP: If your application fails to start, check the log file written to TIP: If your application fails to start, check the log file written to `/var/log/<appname>.log` for errors.
`/var/log/<appname>.log` for errors.
You can also flag the application to start automatically by using your standard operating You can also flag the application to start automatically by using your standard operating system tools.
system tools. For example, on Debian, you could use the following command: For example, on Debian, you could use the following command:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -553,16 +485,12 @@ system tools. For example, on Debian, you could use the following command: ...@@ -553,16 +485,12 @@ system tools. For example, on Debian, you could use the following command:
[[deployment-initd-service-securing]] [[deployment-initd-service-securing]]
===== Securing an `init.d` Service ===== 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.
NOTE: The following is a set of guidelines on how to secure a Spring Boot application that 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 who owns the jar file.
runs as an init.d service. It is not intended to be an exhaustive list of everything that You should never run a Spring Boot application as `root`, so your application's jar file should never be owned by root.
should be done to harden an application and the environment in which it runs. Instead, create a specific user to run your application and use `chown` to make it the owner of the jar file, as shown in the following example:
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 who owns the jar file. You
should never run a Spring Boot application as `root`, so your application's jar file
should never be owned by root. Instead, create a specific user to run your application and
use `chown` to make it the owner of the jar file, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -571,23 +499,20 @@ use `chown` to make it the owner of the jar file, as shown in the following exam ...@@ -571,23 +499,20 @@ use `chown` to make it the owner of the jar file, as shown in the following exam
In this case, the default executable script runs the application as the `bootapp` user. 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 TIP: To reduce the chances of the application's user account being compromised, you should consider preventing it from using a login shell.
consider preventing it from using a login shell. For example, you can set the account's For example, you can set the account's shell to `/usr/sbin/nologin`.
shell to `/usr/sbin/nologin`.
You should also take steps to prevent the modification of your application's jar file. 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 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:
executed by its owner, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ chmod 500 your-app.jar $ chmod 500 your-app.jar
---- ----
Second, you should also take steps to limit the damage if your application or the account Second, you should also take steps to limit the damage if your application or the account that's running it is compromised.
that's running it is compromised. If an attacker does gain access, they could make the jar If an attacker does gain access, they could make the jar file writable and change its contents.
file writable and change its contents. One way to protect against this is to make it One way to protect against this is to make it immutable by using `chattr`, as shown in the following example:
immutable by using `chattr`, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -596,11 +521,8 @@ immutable by using `chattr`, as shown in the following example: ...@@ -596,11 +521,8 @@ immutable by using `chattr`, as shown in the following example:
This will prevent any user, including root, from modifying the jar. This will prevent any user, including root, from modifying the jar.
If root is used to control the application's service and you 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.
<<deployment-script-customization-conf-file, use a `.conf` file>> to customize its 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:
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"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -612,14 +534,11 @@ make root the owner, as shown in the following example: ...@@ -612,14 +534,11 @@ make root the owner, as shown in the following example:
[[deployment-systemd-service]] [[deployment-systemd-service]]
==== Installation as a `systemd` Service ==== Installation as a `systemd` Service
`systemd` is the successor of the System V init system and is now being used by many `systemd` is the successor of the System V init system and is now being used by many modern Linux distributions.
modern Linux distributions. Although you can continue to use `init.d` scripts with 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.
`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 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.
Spring Boot application as a `systemd` service, create a script named `myapp.service` and The following script offers an example:
place it in `/etc/systemd/system` directory. The following script offers an example:
[indent=0] [indent=0]
---- ----
...@@ -636,17 +555,12 @@ place it in `/etc/systemd/system` directory. The following script offers an exam ...@@ -636,17 +555,12 @@ place it in `/etc/systemd/system` directory. The following script offers an exam
WantedBy=multi-user.target WantedBy=multi-user.target
---- ----
IMPORTANT: Remember to change the `Description`, `User`, and `ExecStart` fields for your IMPORTANT: Remember to change the `Description`, `User`, and `ExecStart` fields for your application.
application.
NOTE: The `ExecStart` field does not declare the script action command, which means that NOTE: The `ExecStart` field does not declare the script action command, which means that the `run` command is used by default.
the `run` command is used by default.
Note that, unlike when running as an `init.d` service, the user that runs the application, 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.
the PID file, and the console log file are managed by `systemd` itself and therefore must Consult the https://www.freedesktop.org/software/systemd/man/systemd.service.html[service unit configuration man page] for more details.
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: To flag the application to start automatically on system boot, use the following command:
...@@ -661,197 +575,180 @@ Refer to `man systemctl` for more details. ...@@ -661,197 +575,180 @@ Refer to `man systemctl` for more details.
[[deployment-script-customization]] [[deployment-script-customization]]
==== Customizing the Startup Script ==== Customizing the Startup Script
The default embedded startup script written by the Maven or Gradle plugin can be The default embedded startup script written by the Maven or Gradle plugin can be customized in a number of ways.
customized in a number of ways. For most people, using the default script along with a few For most people, using the default script along with a few customizations is usually enough.
customizations is usually enough. If you find you cannot customize something that you need If you find you cannot customize something that you need to, use the `embeddedLaunchScript` option to write your own file entirely.
to, use the `embeddedLaunchScript` option to write your own file entirely.
[[deployment-script-customization-when-it-written]] [[deployment-script-customization-when-it-written]]
===== Customizing the Start Script when It Is 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 It often makes sense to customize elements of the start script as it is written into the jar file.
jar file. For example, init.d scripts can provide a "`description`". Since you know the For example, init.d scripts can provide a "`description`".
description up front (and it need not change), you may as well provide it when the jar is Since you know the description up front (and it need not change), you may as well provide it when the jar is generated.
generated.
To customize written elements, use the `embeddedLaunchScriptProperties` option of the To customize written elements, use the `embeddedLaunchScriptProperties` option of the Spring Boot Maven plugin or the {spring-boot-gradle-plugin-reference}/#packaging-executable-configuring-launch-script[`properties` property of the Spring Boot Gradle plugin's `launchScript`].
Spring Boot Maven plugin or the
{spring-boot-gradle-plugin-reference}/#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: The following property substitutions are supported with the default script:
[cols="1,3,3,3"] [cols="1,3,3,3"]
|=== |===
|Name |Description |Gradle default |Maven default | Name | Description | Gradle default | Maven default
|`mode` | `mode`
|The script mode. | The script mode.
|`auto` | `auto`
|`auto` | `auto`
|`initInfoProvides` | `initInfoProvides`
|The `Provides` section of "`INIT INFO`" | The `Provides` section of "`INIT INFO`"
|`${task.baseName}` | `${task.baseName}`
|`${project.artifactId}` | `${project.artifactId}`
|`initInfoRequiredStart` | `initInfoRequiredStart`
|`Required-Start` section of "`INIT INFO`". | `Required-Start` section of "`INIT INFO`".
|`$remote_fs $syslog $network` | `$remote_fs $syslog $network`
|`$remote_fs $syslog $network` | `$remote_fs $syslog $network`
|`initInfoRequiredStop` | `initInfoRequiredStop`
|`Required-Stop` section of "`INIT INFO`". | `Required-Stop` section of "`INIT INFO`".
|`$remote_fs $syslog $network` | `$remote_fs $syslog $network`
|`$remote_fs $syslog $network` | `$remote_fs $syslog $network`
|`initInfoDefaultStart` | `initInfoDefaultStart`
|`Default-Start` section of "`INIT INFO`". | `Default-Start` section of "`INIT INFO`".
|`2 3 4 5` | `2 3 4 5`
|`2 3 4 5` | `2 3 4 5`
|`initInfoDefaultStop` | `initInfoDefaultStop`
|`Default-Stop` section of "`INIT INFO`". | `Default-Stop` section of "`INIT INFO`".
|`0 1 6` | `0 1 6`
|`0 1 6` | `0 1 6`
|`initInfoShortDescription` | `initInfoShortDescription`
|`Short-Description` section of "`INIT INFO`". | `Short-Description` section of "`INIT INFO`".
|Single-line version of `${project.description}` (falling back to `${task.baseName}`) | Single-line version of `${project.description}` (falling back to `${task.baseName}`)
|`${project.name}` | `${project.name}`
|`initInfoDescription` | `initInfoDescription`
|`Description` section of "`INIT INFO`". | `Description` section of "`INIT INFO`".
|`${project.description}` (falling back to `${task.baseName}`) | `${project.description}` (falling back to `${task.baseName}`)
|`${project.description}` (falling back to `${project.name}`) | `${project.description}` (falling back to `${project.name}`)
|`initInfoChkconfig` | `initInfoChkconfig`
|`chkconfig` section of "`INIT INFO`" | `chkconfig` section of "`INIT INFO`"
|`2345 99 01` | `2345 99 01`
|`2345 99 01` | `2345 99 01`
|`confFolder` | `confFolder`
|The default value for `CONF_FOLDER` | The default value for `CONF_FOLDER`
|Folder containing the jar | Folder containing the jar
|Folder containing the jar | Folder containing the jar
|`inlinedConfScript` | `inlinedConfScript`
|Reference to a file script that should be inlined in the default launch script. | 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 This can be used to set environmental variables such as `JAVA_OPTS` before any external config files are loaded
config files are loaded
| |
| |
|`logFolder` | `logFolder`
|Default value for `LOG_FOLDER`. Only valid for an `init.d` service | Default value for `LOG_FOLDER`. Only valid for an `init.d` service
| |
| |
|`logFilename` | `logFilename`
|Default value for `LOG_FILENAME`. Only valid for an `init.d` service | Default value for `LOG_FILENAME`. Only valid for an `init.d` service
| |
| |
|`pidFolder` | `pidFolder`
|Default value for `PID_FOLDER`. Only valid for an `init.d` service | Default value for `PID_FOLDER`. Only valid for an `init.d` service
| |
| |
|`pidFilename` | `pidFilename`
|Default value for the name of the PID file in `PID_FOLDER`. Only valid for an | Default value for the name of the PID file in `PID_FOLDER`.
`init.d` service Only valid for an `init.d` service
| |
| |
|`useStartStopDaemon` | `useStartStopDaemon`
|Whether the `start-stop-daemon` command, when it's available, should be used to control | Whether the `start-stop-daemon` command, when it's available, should be used to control the process
the process | `true`
|`true` | `true`
|`true`
|`stopWaitTime` | `stopWaitTime`
|Default value for `STOP_WAIT_TIME` in seconds. Only valid for an `init.d` service | Default value for `STOP_WAIT_TIME` in seconds. Only valid for an `init.d` service
|60 | 60
|60 | 60
|=== |===
[[deployment-script-customization-when-it-runs]] [[deployment-script-customization-when-it-runs]]
===== Customizing a Script 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 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>>.
can use environment variables or a <<deployment-script-customization-conf-file, config
file>>.
The following environment properties are supported with the default script: The following environment properties are supported with the default script:
[cols="1,6"] [cols="1,6"]
|=== |===
|Variable |Description | Variable | Description
|`MODE` | `MODE`
|The "`mode`" of operation. The default depends on the way the jar was built but is | The "`mode`" of operation.
usually `auto` (meaning it tries to guess if it is an init script by checking if it is a 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`).
symlink in a directory called `init.d`). You can explicitly set it to `service` so that 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.
the `stop\|start\|status\|restart` commands work or to `run` if you want to run the
script in the foreground.
|`USE_START_STOP_DAEMON` | `USE_START_STOP_DAEMON`
|Whether the `start-stop-daemon` command, when it's available, should be used to control | Whether the `start-stop-daemon` command, when it's available, should be used to control the process.
the process. Defaults to `true`. Defaults to `true`.
|`PID_FOLDER` | `PID_FOLDER`
|The root name of the pid folder (`/var/run` by default). | The root name of the pid folder (`/var/run` by default).
|`LOG_FOLDER` | `LOG_FOLDER`
|The name of the folder in which to put log files (`/var/log` by default). | The name of the folder in which to put log files (`/var/log` by default).
|`CONF_FOLDER` | `CONF_FOLDER`
|The name of the folder from which to read .conf files (same folder as jar-file by | The name of the folder from which to read .conf files (same folder as jar-file by default).
default).
|`LOG_FILENAME` | `LOG_FILENAME`
|The name of the log file in the `LOG_FOLDER` (`<appname>.log` by default). | The name of the log file in the `LOG_FOLDER` (`<appname>.log` by default).
|`APP_NAME` | `APP_NAME`
|The name of the app. If the jar is run from a symlink, the script guesses the app name. | The name of the app.
If it is not a symlink or you want to explicitly set the app name, this can be useful. 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` | `RUN_ARGS`
|The arguments to pass to the program (the Spring Boot app). | The arguments to pass to the program (the Spring Boot app).
|`JAVA_HOME` | `JAVA_HOME`
|The location of the `java` executable is discovered by using the `PATH` by default, but | 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`.
you can set it explicitly if there is an executable file at `$JAVA_HOME/bin/java`.
|`JAVA_OPTS` | `JAVA_OPTS`
|Options that are passed to the JVM when it is launched. | Options that are passed to the JVM when it is launched.
|`JARFILE` | `JARFILE`
|The explicit location of the jar file, in case the script is being used to launch a jar | The explicit location of the jar file, in case the script is being used to launch a jar that it is not actually embedded.
that it is not actually embedded.
|`DEBUG` | `DEBUG`
|If not empty, sets the `-x` flag on the shell process, making it easy to see the logic | If not empty, sets the `-x` flag on the shell process, making it easy to see the logic in the script.
in the script.
|`STOP_WAIT_TIME` | `STOP_WAIT_TIME`
|The time in seconds to wait when stopping the application before forcing a shutdown (`60` | The time in seconds to wait when stopping the application before forcing a shutdown (`60` by default).
by default).
|=== |===
NOTE: The `PID_FOLDER`, `LOG_FOLDER`, and `LOG_FILENAME` variables are only valid for an 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.
`init.d` service. For `systemd`, the equivalent customizations are made by using the See the https://www.freedesktop.org/software/systemd/man/systemd.service.html[service unit configuration man page] for more details.
'`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]] [[deployment-script-customization-conf-file]]
With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding section can be configured by using a `.conf` file.
section can be configured by using a `.conf` file. The file is expected to be next to the The file is expected to be next to the jar file and have the same name but suffixed with `.conf` rather than `.jar`.
jar file and have the same name but suffixed with `.conf` rather than `.jar`. For example, For example, a jar named `/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`, as shown in the following 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 .myapp.conf
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
...@@ -860,33 +757,24 @@ a jar named `/var/myapp/myapp.jar` uses the configuration file named ...@@ -860,33 +757,24 @@ a jar named `/var/myapp/myapp.jar` uses the configuration file named
LOG_FOLDER=/custom/log/folder LOG_FOLDER=/custom/log/folder
---- ----
TIP: If you do not like having the config file next to the jar file, you can set a 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.
`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>>.
To learn about securing this file appropriately, see
<<deployment-initd-service-securing,the guidelines for securing an init.d service>>.
[[deployment-windows]] [[deployment-windows]]
=== Microsoft Windows Services === Microsoft Windows Services
A Spring Boot application can be started as a Windows service by using A Spring Boot application can be started as a Windows service by using https://github.com/kohsuke/winsw[`winsw`].
https://github.com/kohsuke/winsw[`winsw`].
A (https://github.com/snicoll-scratches/spring-boot-daemon[separately maintained sample]) 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.
describes step-by-step how you can create a Windows service for your Spring Boot
application.
[[deployment-whats-next]] [[deployment-whats-next]]
== What to Read Next == What to Read Next
Check out the https://www.cloudfoundry.org/[Cloud Foundry], 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.
https://www.heroku.com/[Heroku], https://www.openshift.com[OpenShift], and These are just four of the most popular Java PaaS providers.
https://boxfuse.com[Boxfuse] web sites for more information about the kinds of features Since Spring Boot is so amenable to cloud-based deployment, you can freely consider other providers as well.
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 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>>_.
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>>_.
...@@ -3,26 +3,23 @@ ...@@ -3,26 +3,23 @@
[partintro] [partintro]
-- --
This section provides a brief overview of Spring Boot reference documentation. It serves This section provides a brief overview of Spring Boot reference documentation.
as a map for the rest of the document. It serves as a map for the rest of the document.
-- --
[[boot-documentation-about]] [[boot-documentation-about]]
== About the Documentation == About the Documentation
The Spring Boot reference guide is available as The Spring Boot reference guide is available as:
* {spring-boot-docs}/html[HTML] * {spring-boot-docs}/html[HTML]
* {spring-boot-docs}/pdf/spring-boot-reference.pdf[PDF] * {spring-boot-docs}/pdf/spring-boot-reference.pdf[PDF]
* {spring-boot-docs}/epub/spring-boot-reference.epub[EPUB] * {spring-boot-docs}/epub/spring-boot-reference.epub[EPUB]
The latest copy The latest copy is available at {spring-boot-docs-current}.
is available at {spring-boot-docs-current}.
Copies of this document may be made for your own use and for distribution to others, 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.
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.
...@@ -30,63 +27,39 @@ copy contains this Copyright Notice, whether distributed in print or electronica ...@@ -30,63 +27,39 @@ copy contains this Copyright Notice, whether distributed in print or electronica
== Getting Help == Getting Help
If you have trouble with Spring Boot, we would like to 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 * Try the <<howto.adoc#howto, How-to documents>>.
common questions. They provide solutions to the most common questions.
* Learn the Spring basics. Spring Boot builds on many other Spring projects. Check the * Learn the Spring basics.
https://spring.io[spring.io] web-site for a wealth of reference documentation. If you are Spring Boot builds on many other Spring projects.
starting out with Spring, try one of the https://spring.io/guides[guides]. Check the https://spring.io[spring.io] web-site for a wealth of reference documentation.
* Ask a question. We monitor https://stackoverflow.com[stackoverflow.com] for questions If you are starting out with Spring, try one of the https://spring.io/guides[guides].
tagged with https://stackoverflow.com/tags/spring-boot[`spring-boot`]. * 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. * 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 NOTE: All of Spring Boot is open source, including the documentation.
problems with the docs or if you want to improve them, please {github-code}[get If you find problems with the docs or if you want to improve them, please {github-code}[get involved].
involved].
[[boot-documentation-first-steps]] [[boot-documentation-first-steps]]
== First Steps == First Steps
If you are getting started with Spring Boot or 'Spring' in general, start with If you are getting started with Spring Boot or 'Spring' in general, start with <<getting-started.adoc#getting-started, the following topics>>:
<<getting-started.adoc#getting-started, the following topics>>:
* *From scratch:* * *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>>
<<getting-started.adoc#getting-started-introducing-spring-boot, Overview>> | * *Tutorial:* <<getting-started.adoc#getting-started-first-application, Part 1>> | <<getting-started.adoc#getting-started-first-application-code, Part 2>>
<<getting-started.adoc#getting-started-system-requirements, Requirements>> | * *Running your example:* <<getting-started.adoc#getting-started-first-application-run, Part 1>> | <<getting-started.adoc#getting-started-first-application-executable-jar, Part 2>>
<<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 == Working with Spring Boot
Ready to actually start using Spring Boot? <<using-spring-boot.adoc#using-boot, We have Ready to actually start using Spring Boot? <<using-spring-boot.adoc#using-boot, we have you covered>>:
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>>
* *Build systems:* * *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>>
<<using-spring-boot.adoc#using-boot-maven, Maven>> | * *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>>
<<using-spring-boot.adoc#using-boot-gradle, Gradle>> | * *Packaging your app:* <<using-spring-boot.adoc#using-boot-packaging-for-production, Production jars>>
<<using-spring-boot.adoc#using-boot-ant, Ant>> | * *Spring Boot CLI:* <<spring-boot-cli.adoc#cli, Using the CLI>>
<<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>>
...@@ -94,62 +67,28 @@ Dependency Injection>> ...@@ -94,62 +67,28 @@ Dependency Injection>>
Need more details about Spring Boot's core features? Need more details about Spring Boot's core features?
<<spring-boot-features.adoc#boot-features, The following content is for you>>: <<spring-boot-features.adoc#boot-features, The following content is for you>>:
* *Core Features:* * *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>>
<<spring-boot-features.adoc#boot-features-spring-application, SpringApplication>> | * *Web Applications:* <<spring-boot-features.adoc#boot-features-spring-mvc, MVC>> | <<spring-boot-features.adoc#boot-features-embedded-container, Embedded Containers>>
<<spring-boot-features.adoc#boot-features-external-config, External Configuration>> | * *Working with data:* <<spring-boot-features.adoc#boot-features-sql, SQL>> | <<spring-boot-features.adoc#boot-features-nosql, NO-SQL>>
<<spring-boot-features.adoc#boot-features-profiles, Profiles>> | * *Messaging:* <<spring-boot-features.adoc#boot-features-messaging, Overview>> | <<spring-boot-features.adoc#boot-features-jms, JMS>>
<<spring-boot-features.adoc#boot-features-logging, Logging>> * *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>>
* *Web Applications:* * *Extending:* <<spring-boot-features.adoc#boot-features-developing-auto-configuration, Auto-configuration>> | <<spring-boot-features.adoc#boot-features-condition-annotations, @Conditions>>
<<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 == Moving to Production
When you are ready to push your Spring Boot application to production, we have 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:
<<production-ready-features.adoc#production-ready, some tricks>> that you might like:
* *Management endpoints:* * *Management endpoints:* <<production-ready-features.adoc#production-ready-endpoints, Overview>> | <<production-ready-features.adoc#production-ready-customizing-endpoints, Customization>>
<<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>>
<<production-ready-features.adoc#production-ready-customizing-endpoints, Customization>> * *Monitoring:* <<production-ready-features.adoc#production-ready-metrics, Metrics>> | <<production-ready-features.adoc#production-ready-auditing, Auditing>> | <<production-ready-features.adoc#production-ready-tracing, Tracing>> | <<production-ready-features.adoc#production-ready-process-monitoring, Process>>
* *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-tracing, Tracing>> |
<<production-ready-features.adoc#production-ready-process-monitoring, Process>>
== Advanced Topics == Advanced Topics
Finally, we have a few topics for more advanced users: Finally, we have a few topics for more advanced users:
* *Spring Boot Applications Deployment:* * *Spring Boot Applications Deployment:* <<deployment.adoc#cloud-deployment, Cloud Deployment>> | <<deployment.adoc#deployment-service, OS Service>>
<<deployment.adoc#cloud-deployment, Cloud Deployment>> | * *Build tool plugins:* <<build-tool-plugins.adoc#build-tool-plugins-maven-plugin, Maven>> | <<build-tool-plugins.adoc#build-tool-plugins-gradle-plugin, Gradle>>
<<deployment.adoc#deployment-service, OS Service>> * *Appendix:* <<appendix-application-properties.adoc#common-application-properties, Application Properties>> | <<appendix-auto-configuration-classes.adoc#auto-configuration-classes, Auto-configuration classes>> | <<appendix-executable-jar-format.adoc#executable-jar, Executable Jars>>
* *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-auto-configuration-classes.adoc#auto-configuration-classes, Auto-configuration
classes>> |
<<appendix-executable-jar-format.adoc#executable-jar, Executable Jars>>
...@@ -3,55 +3,47 @@ ...@@ -3,55 +3,47 @@
[partintro] [partintro]
-- --
If you are getting started with Spring Boot, or "`Spring`" in general, start by reading If you are getting started with Spring Boot, or "`Spring`" in general, start by reading this section.
this section. It answers the basic "`what?`", "`how?`" and "`why?`" questions. It It answers the basic "`what?`", "`how?`" and "`why?`" questions.
includes an introduction to Spring Boot, along with installation instructions. We then It includes an introduction to Spring Boot, along with installation instructions.
walk you through building your first Spring Boot application, discussing some core We then walk you through building your first Spring Boot application, discussing some core principles as we go.
principles as we go.
-- --
[[getting-started-introducing-spring-boot]] [[getting-started-introducing-spring-boot]]
== Introducing Spring Boot == Introducing Spring Boot
Spring Boot makes it easy to create stand-alone, production-grade Spring-based Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run.
Applications that you can run. We take an opinionated view of the Spring platform and We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss.
third-party libraries, so that you can get started with minimum fuss. Most Spring Boot Most Spring Boot applications need very little Spring configuration.
applications need very little Spring configuration.
You can use Spring Boot to create Java applications that can be started by using You can use Spring Boot to create Java applications that can be started by using `java -jar` or more traditional war deployments.
`java -jar` or more traditional war deployments. We also provide a command line tool that We also provide a command line tool that runs "`spring scripts`".
runs "`spring scripts`".
Our primary goals are: Our primary goals are:
* Provide a radically faster and widely accessible getting-started experience for all * Provide a radically faster and widely accessible getting-started experience for all Spring development.
Spring development. * Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
* Be opinionated out of the box but get out of the way quickly as requirements start to * 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).
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. * Absolutely no code generation and no requirement for XML configuration.
[[getting-started-system-requirements]] [[getting-started-system-requirements]]
== System Requirements == System Requirements
Spring Boot {spring-boot-version} requires https://www.java.com[Java 8] and is compatible Spring Boot {spring-boot-version} requires https://www.java.com[Java 8] and is compatible up to Java 12 (included).
up to Java 12 (included). {spring-reference}[Spring Framework {spring-framework-version}] {spring-reference}[Spring Framework {spring-framework-version}] or above is also required.
or above is also required.
Explicit build support is provided for the following build tools: Explicit build support is provided for the following build tools:
|=== |===
|Build Tool |Version | Build Tool | Version
|Maven | Maven
|3.3+ | 3.3+
|Gradle | Gradle
|4.4+ | 4.4+
|=== |===
...@@ -61,16 +53,16 @@ Explicit build support is provided for the following build tools: ...@@ -61,16 +53,16 @@ Explicit build support is provided for the following build tools:
Spring Boot supports the following embedded servlet containers: Spring Boot supports the following embedded servlet containers:
|=== |===
|Name |Servlet Version | Name | Servlet Version
|Tomcat 9.0 | Tomcat 9.0
|4.0 | 4.0
|Jetty 9.4 | Jetty 9.4
|3.1 | 3.1
|Undertow 2.0 | Undertow 2.0
|4.0 | 4.0
|=== |===
You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container. You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container.
...@@ -79,50 +71,44 @@ You can also deploy Spring Boot applications to any Servlet 3.1+ compatible cont ...@@ -79,50 +71,44 @@ You can also deploy Spring Boot applications to any Servlet 3.1+ compatible cont
[[getting-started-installing-spring-boot]] [[getting-started-installing-spring-boot]]
== Installing Spring Boot == Installing Spring Boot
Spring Boot can be used with "`classic`" Java development tools or installed as a command Spring Boot can be used with "`classic`" Java development tools or installed as a command line tool.
line tool. Either way, you need https://www.java.com[Java SDK v1.8] or higher. Before you Either way, you need https://www.java.com[Java SDK v1.8] or higher.
begin, you should check your current Java installation by using the following command: Before you begin, you should check your current Java installation by using the following command:
[indent=0] [indent=0]
---- ----
$ java -version $ java -version
---- ----
If you are new to Java development or if you want to experiment with Spring Boot, you 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.
might want to try the <<getting-started-installing-the-cli, Spring Boot CLI>> (Command Otherwise, read on for "`classic`" installation instructions.
Line Interface) first. Otherwise, read on for "`classic`" installation instructions.
[[getting-started-installation-instructions-for-java]] [[getting-started-installation-instructions-for-java]]
=== Installation Instructions for the Java Developer === Installation Instructions for the Java Developer
You can use Spring Boot in the same way as any standard Java library. To do so, include You can use Spring Boot in the same way as any standard Java library.
the appropriate `+spring-boot-*.jar+` files on your classpath. Spring Boot does not To do so, include the appropriate `+spring-boot-*.jar+` files on your classpath.
require any special tools integration, so you can use any IDE or text editor. Also, there Spring Boot does not require any special tools integration, so you can use any IDE or text editor.
is nothing special about a Spring Boot application, so you can run and debug a Spring 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.
Boot application as you would any other Java program.
Although you _could_ copy Spring Boot jars, we generally recommend that you use a build 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).
tool that supports dependency management (such as Maven or Gradle).
[[getting-started-maven-installation]] [[getting-started-maven-installation]]
==== Maven Installation ==== Maven Installation
Spring Boot is compatible with Apache Maven 3.3 or above. If you do not already have Spring Boot is compatible with Apache Maven 3.3 or above.
Maven installed, you can follow the instructions at https://maven.apache.org. 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 TIP: On many operating systems, Maven can be installed with a package manager.
OSX Homebrew, try `brew install maven`. Ubuntu users can run If you use OSX Homebrew, try `brew install maven`.
`sudo apt-get install maven`. Windows users with https://chocolatey.org/[Chocolatey] can Ubuntu users can run `sudo apt-get install maven`.
run `choco install maven` from an elevated (administrator) prompt. 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 Spring Boot dependencies use the `org.springframework.boot` `groupId`.
Maven POM file inherits from the `spring-boot-starter-parent` project and declares 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`">>.
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.
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: The following listing shows a typical `pom.xml` file:
...@@ -190,47 +176,38 @@ endif::[] ...@@ -190,47 +176,38 @@ endif::[]
</project> </project>
---- ----
TIP: The `spring-boot-starter-parent` is a great way to use Spring Boot, but it might not TIP: The `spring-boot-starter-parent` is a great way to use Spring Boot, but it might not be suitable all of the time.
be suitable all of the time. Sometimes you may need to inherit from a different parent Sometimes you may need to inherit from a different parent POM, or you might not like our default settings.
POM, or you might not like our default settings. In those cases, see In those cases, see <<using-boot-maven-without-a-parent>> for an alternative solution that uses an `import` scope.
<<using-boot-maven-without-a-parent>> for an alternative solution that uses an `import`
scope.
[[getting-started-gradle-installation]] [[getting-started-gradle-installation]]
==== Gradle Installation ==== Gradle Installation
Spring Boot is compatible with Gradle 4.4 and later. If you do not already have Gradle Spring Boot is compatible with Gradle 4.4 and later.
installed, you can follow the instructions at https://gradle.org. 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`. Spring Boot dependencies can be declared by using the `org.springframework.boot` `group`.
Typically, your project declares dependencies to one or more Typically, your project declares dependencies to one or more <<using-spring-boot.adoc#using-boot-starter, "`Starters`">>.
<<using-spring-boot.adoc#using-boot-starter, "`Starters`">>. Spring Boot 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.
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 .Gradle Wrapper
**** ****
The Gradle Wrapper provides a nice way of "`obtaining`" Gradle when you need to build a The Gradle Wrapper provides a nice way of "`obtaining`" Gradle when you need to build a project.
project. It is a small script and library that you commit alongside your code to It is a small script and library that you commit alongside your code to bootstrap the build process.
bootstrap the build process. See {gradle-user-guide}/gradle_wrapper.html for details. See {gradle-user-guide}/gradle_wrapper.html for details.
**** ****
More details on getting started with Spring Boot and Gradle can be found in the More details on getting started with Spring Boot and Gradle can be found in the {spring-boot-gradle-plugin-reference}/#getting-started[Getting Started section] of the Gradle plugin's reference guide.
{spring-boot-gradle-plugin-reference}/#getting-started[Getting Started section] of the
Gradle plugin's reference guide.
[[getting-started-installing-the-cli]] [[getting-started-installing-the-cli]]
=== Installing the Spring Boot CLI === Installing the Spring Boot CLI
The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to quickly prototype with Spring.
quickly prototype with Spring. It lets you run http://groovy-lang.org/[Groovy] scripts, 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.
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 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.
quickest way to get a Spring application off the ground.
...@@ -242,24 +219,18 @@ You can download the Spring CLI distribution from the Spring software repository ...@@ -242,24 +219,18 @@ You can download the Spring CLI distribution from the Spring software repository
* https://repo.spring.io/{spring-boot-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] * https://repo.spring.io/{spring-boot-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 Cutting edge
https://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/[snapshot https://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/[snapshot distributions] are also available.
distributions] are also available.
Once downloaded, follow the Once downloaded, follow the {github-raw}/spring-boot-project/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] instructions from the unpacked archive.
{github-raw}/spring-boot-project/spring-boot-cli/src/main/content/INSTALL.txt[INSTALL.txt] In summary, there is a `spring` script (`spring.bat` for Windows) in a `bin/` directory in the `.zip` file.
instructions from the unpacked archive. In summary, there is a `spring` script Alternatively, you can use `java -jar` with the `.jar` file (the script helps you to be sure that the classpath is set correctly).
(`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]] [[getting-started-sdkman-cli-installation]]
==== Installation with SDKMAN! ==== Installation with SDKMAN!
SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI.
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:
Get SDKMAN! from https://sdkman.io and install Spring Boot by using the following
commands:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -268,8 +239,7 @@ commands: ...@@ -268,8 +239,7 @@ commands:
Spring Boot v{spring-boot-version} Spring Boot v{spring-boot-version}
---- ----
If you develop features for the CLI and want easy access to the version you built, If you develop features for the CLI and want easy access to the version you built, use the following commands:
use the following commands:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -279,9 +249,8 @@ use the following commands: ...@@ -279,9 +249,8 @@ use the following commands:
Spring CLI v{spring-boot-version} Spring CLI v{spring-boot-version}
---- ----
The preceding instructions install a local instance of `spring` called the `dev` The preceding instructions install a local instance of `spring` called the `dev` instance.
instance. It points at your target build location, so every time you rebuild Spring Boot, It points at your target build location, so every time you rebuild Spring Boot, `spring` is up-to-date.
`spring` is up-to-date.
You can see it by running the following command: You can see it by running the following command:
...@@ -306,8 +275,7 @@ You can see it by running the following command: ...@@ -306,8 +275,7 @@ You can see it by running the following command:
[[getting-started-homebrew-cli-installation]] [[getting-started-homebrew-cli-installation]]
==== OSX Homebrew Installation ==== OSX Homebrew Installation
If you are on a Mac and use https://brew.sh/[Homebrew], you can install the Spring Boot If you are on a Mac and use https://brew.sh/[Homebrew], you can install the Spring Boot CLI by using the following commands:
CLI by using the following commands:
[indent=0] [indent=0]
---- ----
...@@ -317,15 +285,14 @@ CLI by using the following commands: ...@@ -317,15 +285,14 @@ CLI by using the following commands:
Homebrew installs `spring` to `/usr/local/bin`. 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 NOTE: If you do not see the formula, your installation of brew might be out-of-date.
that case, run `brew update` and try again. In that case, run `brew update` and try again.
[[getting-started-macports-cli-installation]] [[getting-started-macports-cli-installation]]
==== MacPorts Installation ==== MacPorts Installation
If you are on a Mac and use https://www.macports.org/[MacPorts], you can install the 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:
Spring Boot CLI by using the following command:
[indent=0] [indent=0]
---- ----
...@@ -336,14 +303,10 @@ Spring Boot CLI by using the following command: ...@@ -336,14 +303,10 @@ Spring Boot CLI by using the following command:
[[getting-started-cli-command-line-completion]] [[getting-started-cli-command-line-completion]]
==== Command-line Completion ==== Command-line Completion
The Spring Boot CLI includes scripts that provide command completion for the 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.
https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29[BASH] and You can `source` the script (also named `spring`) in any shell or put it in your personal or system-wide bash completion initialization.
https://en.wikipedia.org/wiki/Z_shell[zsh] shells. You can `source` the script (also named 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.
`spring`) in any shell or put it in your personal or system-wide bash completion For example, to run the script manually if you have installed by using SDKMAN!, use the following commands:
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] [indent=0]
---- ----
...@@ -352,15 +315,13 @@ use the following commands: ...@@ -352,15 +315,13 @@ use the following commands:
grab help jar run test version grab help jar run test version
---- ----
NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line NOTE: If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line completion scripts are automatically registered with your shell.
completion scripts are automatically registered with your shell.
[[getting-started-scoop-cli-installation]] [[getting-started-scoop-cli-installation]]
==== Windows Scoop Installation ==== Windows Scoop Installation
If you are on a Windows and use https://scoop.sh/[Scoop], you can install the Spring Boot If you are on a Windows and use https://scoop.sh/[Scoop], you can install the Spring Boot CLI by using the following commands:
CLI by using the following commands:
[indent=0] [indent=0]
---- ----
...@@ -377,8 +338,8 @@ In that case, run `scoop update` and try again. ...@@ -377,8 +338,8 @@ In that case, run `scoop update` and try again.
[[getting-started-cli-example]] [[getting-started-cli-example]]
==== Quick-start Spring CLI Example ==== Quick-start Spring CLI Example
You can use the following web application to test your installation. To start, create a You can use the following web application to test your installation.
file called `app.groovy`, as follows: To start, create a file called `app.groovy`, as follows:
[source,groovy,indent=0,subs="verbatim,quotes,attributes"] [source,groovy,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -403,8 +364,8 @@ Then run it from a shell, as follows: ...@@ -403,8 +364,8 @@ Then run it from a shell, as follows:
NOTE: The first run of your application is slow, as dependencies are downloaded. NOTE: The first run of your application is slow, as dependencies are downloaded.
Subsequent runs are much quicker. Subsequent runs are much quicker.
Open `http://localhost:8080` in your favorite web browser. You should see the following Open `http://localhost:8080` in your favorite web browser.
output: You should see the following output:
[indent=0] [indent=0]
---- ----
...@@ -415,16 +376,12 @@ output: ...@@ -415,16 +376,12 @@ output:
[[getting-started-upgrading-from-an-earlier-version]] [[getting-started-upgrading-from-an-earlier-version]]
=== Upgrading from an Earlier Version of Spring Boot === Upgrading from an Earlier Version of Spring Boot
If you are upgrading from an earlier release of Spring Boot, check the 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.
{github-wiki}/Spring-Boot-2.0-Migration-Guide["`migration guide`" on the project wiki] Check also the {github-wiki}["`release notes`"] for a list of "`new and noteworthy`" features for each release.
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. 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 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.
at startup, but also temporarily migrate properties at runtime for you. To enable that To enable that feature, add the following dependency to your project:
feature, add the following dependency to your project:
[source,xml,indent=0] [source,xml,indent=0]
---- ----
...@@ -435,40 +392,31 @@ feature, add the following dependency to your project: ...@@ -435,40 +392,31 @@ feature, add the following dependency to your project:
</dependency> </dependency>
---- ----
WARNING: Properties that are added late to the environment, such as when using WARNING: Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account.
`@PropertySource`, will not be taken into account.
NOTE: Once you're done with the migration, please make sure to remove this module from NOTE: Once you're done with the migration, please make sure to remove this module from your project's dependencies.
your project's dependencies.
To upgrade an existing CLI installation, use the appropriate package manager command (for To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`).
example, `brew upgrade`) or, if you manually installed the CLI, follow the 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-manual-cli-installation, standard instructions>>, remembering to update
your `PATH` environment variable to remove any older references.
[[getting-started-first-application]] [[getting-started-first-application]]
== Developing Your First Spring Boot Application == Developing Your First Spring Boot Application
This section describes how to develop a simple "`Hello World!`" web application that This section describes how to develop a simple "`Hello World!`" web application that highlights some of Spring Boot's key features.
highlights some of Spring Boot's key features. We use Maven to build this project, since We use Maven to build this project, since most IDEs support it.
most IDEs support it.
[TIP] [TIP]
==== ====
The https://spring.io[spring.io] web site contains many "`Getting Started`" The https://spring.io[spring.io] web site contains many "`Getting Started`" https://spring.io/guides[guides] that use Spring Boot.
https://spring.io/guides[guides] that use Spring Boot. If you need to solve a specific If you need to solve a specific problem, check there first.
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.
You can shortcut the steps below by going to https://start.spring.io and choosing the Doing so generates a new project structure so that you can <<getting-started-first-application-code,start coding right away>>.
"Web" starter from the dependencies searcher. Doing so generates a new project structure Check the {spring-initializr-reference}/#user-guide[Spring Initializr documentation] for more details.
so that you can <<getting-started-first-application-code,start coding right away>>. Check
the {spring-initializr-reference}/#user-guide[Spring Initializr documentation] for more
details.
==== ====
Before we begin, open a terminal and run the following commands to ensure that you have Before we begin, open a terminal and run the following commands to ensure that you have valid versions of Java and Maven installed:
valid versions of Java and Maven installed:
[indent=0] [indent=0]
---- ----
...@@ -486,15 +434,16 @@ valid versions of Java and Maven installed: ...@@ -486,15 +434,16 @@ valid versions of Java and Maven installed:
Java version: 1.8.0_102, vendor: Oracle Corporation Java version: 1.8.0_102, vendor: Oracle Corporation
---- ----
NOTE: This sample needs to be created in its own folder. Subsequent instructions assume NOTE: This sample needs to be created in its own folder.
that you have created a suitable folder and that it is your current directory. Subsequent instructions assume that you have created a suitable folder and that it is your current directory.
[[getting-started-first-application-pom]] [[getting-started-first-application-pom]]
=== Creating the POM === Creating the POM
We need to start by creating a Maven `pom.xml` file. The `pom.xml` is the recipe that is We need to start by creating a Maven `pom.xml` file.
used to build your project. Open your favorite text editor and add the following: 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"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -542,29 +491,24 @@ endif::[] ...@@ -542,29 +491,24 @@ endif::[]
</project> </project>
---- ----
The preceding listing should give you a working build. You can test it by running `mvn The preceding listing should give you a working build.
package` (for now, you can ignore the "`jar will be empty - no content was marked for 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).
inclusion!`" warning).
NOTE: At this point, you could import the project into an IDE (most modern Java IDEs NOTE: At this point, you could import the project into an IDE (most modern Java IDEs include built-in support for Maven).
include built-in support for Maven). For simplicity, we continue to use a plain text For simplicity, we continue to use a plain text editor for this example.
editor for this example.
[[getting-started-first-application-dependencies]] [[getting-started-first-application-dependencies]]
=== Adding Classpath Dependencies === Adding Classpath Dependencies
Spring Boot provides a number of "`Starters`" that let you add jars to your classpath. Spring Boot provides a number of "`Starters`" that let you add jars to your classpath.
Our sample application has already used `spring-boot-starter-parent` in the `parent` Our sample application has already used `spring-boot-starter-parent` in the `parent` section of the POM.
section of the POM. The `spring-boot-starter-parent` is a special starter that provides The `spring-boot-starter-parent` is a special starter that provides useful Maven defaults.
useful Maven defaults. It also provides a 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.
<<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 Other "`Starters`" provide dependencies that you are likely to need when developing a specific type of application.
specific type of application. Since we are developing a web application, we add a Since we are developing a web application, we add a `spring-boot-starter-web` dependency.
`spring-boot-starter-web` dependency. Before that, we can look at what we currently have Before that, we can look at what we currently have by running the following command:
by running the following command:
[indent=0] [indent=0]
---- ----
...@@ -573,10 +517,9 @@ by running the following command: ...@@ -573,10 +517,9 @@ by running the following command:
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
---- ----
The `mvn dependency:tree` command prints a tree representation of your project The `mvn dependency:tree` command prints a tree representation of your project dependencies.
dependencies. You can see that `spring-boot-starter-parent` provides no dependencies by You can see that `spring-boot-starter-parent` provides no dependencies by itself.
itself. To add the necessary dependencies, edit your `pom.xml` and add the To add the necessary dependencies, edit your `pom.xml` and add the `spring-boot-starter-web` dependency immediately below the `parent` section:
`spring-boot-starter-web` dependency immediately below the `parent` section:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -588,16 +531,14 @@ itself. To add the necessary dependencies, edit your `pom.xml` and add the ...@@ -588,16 +531,14 @@ itself. To add the necessary dependencies, edit your `pom.xml` and add the
</dependencies> </dependencies>
---- ----
If you run `mvn dependency:tree` again, you see that there are now a number of additional 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.
dependencies, including the Tomcat web server and Spring Boot itself.
[[getting-started-first-application-code]] [[getting-started-first-application-code]]
=== Writing the Code === Writing the Code
To finish our application, we need to create a single Java file. By default, Maven To finish our application, we need to create a single Java file.
compiles sources from `src/main/java`, so you need to create that folder structure and 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:
then add a file named `src/main/java/Example.java` to contain the following code:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -621,64 +562,59 @@ then add a file named `src/main/java/Example.java` to contain the following code ...@@ -621,64 +562,59 @@ then add a file named `src/main/java/Example.java` to contain the following code
} }
---- ----
Although there is not much code here, quite a lot is going on. We step through the Although there is not much code here, quite a lot is going on.
important parts in the next few sections. We step through the important parts in the next few sections.
[[getting-started-first-application-annotations]] [[getting-started-first-application-annotations]]
==== The @RestController and @RequestMapping Annotations ==== The @RestController and @RequestMapping Annotations
The first annotation on our `Example` class is `@RestController`. This is known as a The first annotation on our `Example` class is `@RestController`.
_stereotype_ annotation. It provides hints for people reading the code and for Spring This is known as a _stereotype_ annotation.
that the class plays a specific role. In this case, our class is a web `@Controller`, so It provides hints for people reading the code and for Spring that the class plays a specific role.
Spring considers it when handling incoming web requests. 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 The `@RequestMapping` annotation provides "`routing`" information.
any HTTP request with the `/` path should be mapped to the `home` method. The It tells Spring that any HTTP request with the `/` path should be mapped to the `home` method.
`@RestController` annotation tells Spring to render the resulting string directly back to The `@RestController` annotation tells Spring to render the resulting string directly back to the caller.
the caller.
TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations. TIP: The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations (they are not specific to Spring Boot).
(They are not specific to Spring Boot.) See the {spring-reference}web.html#mvc[MVC See the {spring-reference}web.html#mvc[MVC section] in the Spring Reference Documentation for more details.
section] in the Spring Reference Documentation for more details.
[[getting-started-first-application-auto-configuration]] [[getting-started-first-application-auto-configuration]]
==== The @EnableAutoConfiguration Annotation ==== The @EnableAutoConfiguration Annotation
The second class-level annotation is `@EnableAutoConfiguration`. This annotation tells The second class-level annotation is `@EnableAutoConfiguration`.
Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies This annotation tells Spring Boot to "`guess`" how you want to configure Spring, based on the jar dependencies that you have added.
that you have added. Since `spring-boot-starter-web` added Tomcat and Spring MVC, the 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.
auto-configuration assumes that you are developing a web application and sets up Spring
accordingly.
.Starters and Auto-configuration .Starters and Auto-configuration
**** ****
Auto-configuration is designed to work well with "`Starters`", but the two concepts are Auto-configuration is designed to work well with "`Starters`", but the two concepts are not directly tied.
not directly tied. You are free to pick and choose jar dependencies outside of the You are free to pick and choose jar dependencies outside of the starters.
starters. Spring Boot still does its best to auto-configure your application. Spring Boot still does its best to auto-configure your application.
**** ****
[[getting-started-first-application-main-method]] [[getting-started-first-application-main-method]]
==== The "`main`" Method ==== The "`main`" Method
The final part of our application is the `main` method. This is just a standard method The final part of our application is the `main` method.
that follows the Java convention for an application entry point. Our main method This is just a standard method that follows the Java convention for an application entry point.
delegates to Spring Boot's `SpringApplication` class by calling `run`. Our main method delegates to Spring Boot's `SpringApplication` class by calling `run`.
`SpringApplication` bootstraps our application, starting Spring, which, in turn, starts `SpringApplication` bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.
the auto-configured Tomcat web server. We need to pass `Example.class` as an argument to We need to pass `Example.class` as an argument to the `run` method to tell `SpringApplication` which is the primary Spring component.
the `run` method to tell `SpringApplication` which is the primary Spring component. The The `args` array is also passed through to expose any command-line arguments.
`args` array is also passed through to expose any command-line arguments.
[[getting-started-first-application-run]] [[getting-started-first-application-run]]
=== Running the Example === Running the Example
At this point, your application should work. Since you used the At this point, your application should work.
`spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start Since you used the `spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start the application.
the application. Type `mvn spring-boot:run` from the root project directory to start the Type `mvn spring-boot:run` from the root project directory to start the application.
application. You should see output similar to the following: You should see output similar to the following:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
...@@ -710,29 +646,24 @@ To gracefully exit the application, press `ctrl-c`. ...@@ -710,29 +646,24 @@ To gracefully exit the application, press `ctrl-c`.
[[getting-started-first-application-executable-jar]] [[getting-started-first-application-executable-jar]]
=== Creating an Executable Jar === Creating an Executable Jar
We finish our example by creating a completely self-contained executable jar file that We finish our example by creating a completely self-contained executable jar file that we could run in production.
we could run in production. Executable jars (sometimes called "`fat jars`") are archives 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.
containing your compiled classes along with all of the jar dependencies that your code
needs to run.
.Executable jars and Java .Executable jars and Java
**** ****
Java does not provide a standard way to load nested jar files (jar files that are Java does not provide a standard way to load nested jar files (jar files that are themselves contained within a jar).
themselves contained within a jar). This can be problematic if you are looking to This can be problematic if you are looking to distribute a self-contained application.
distribute a self-contained application.
To solve this problem, many developers use "`uber`" jars.
To solve this problem, many developers use "`uber`" jars. An uber jar packages all the An uber jar packages all the classes from all the application's dependencies into a single archive.
classes from all the application's dependencies into a single archive. The problem with The problem with this approach is that it becomes hard to see which libraries are in your application.
this approach is that it becomes hard to see which libraries are in your application. It It can also be problematic if the same filename is used (but with different content) in multiple jars.
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.
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 To create an executable jar, we need to add the `spring-boot-maven-plugin` to our `pom.xml`.
`pom.xml`. To do so, insert the following lines just below the `dependencies` section: To do so, insert the following lines just below the `dependencies` section:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -746,10 +677,9 @@ To create an executable jar, we need to add the `spring-boot-maven-plugin` to ou ...@@ -746,10 +677,9 @@ To create an executable jar, we need to add the `spring-boot-maven-plugin` to ou
</build> </build>
---- ----
NOTE: The `spring-boot-starter-parent` POM includes `<executions>` configuration to bind NOTE: The `spring-boot-starter-parent` POM includes `<executions>` configuration to bind the `repackage` goal.
the `repackage` goal. If you do not use the parent POM, you need to declare this If you do not use the parent POM, you need to declare this configuration yourself.
configuration yourself. See the {spring-boot-maven-plugin-site}/usage.html[plugin See the {spring-boot-maven-plugin-site}/usage.html[plugin documentation] for details.
documentation] for details.
Save your `pom.xml` and run `mvn package` from the command line, as follows: Save your `pom.xml` and run `mvn package` from the command line, as follows:
...@@ -772,18 +702,17 @@ Save your `pom.xml` and run `mvn package` from the command line, as follows: ...@@ -772,18 +702,17 @@ Save your `pom.xml` and run `mvn package` from the command line, as follows:
[INFO] ------------------------------------------------------------------------ [INFO] ------------------------------------------------------------------------
---- ----
If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`. The If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`.
file should be around 10 MB in size. If you want to peek inside, you can use `jar tvf`, The file should be around 10 MB in size.
as follows: If you want to peek inside, you can use `jar tvf`, as follows:
[indent=0] [indent=0]
---- ----
$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar $ 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 You should also see a much smaller file named `myproject-0.0.1-SNAPSHOT.jar.original` in the `target` directory.
the `target` directory. This is the original jar file that Maven created before it was This is the original jar file that Maven created before it was repackaged by Spring Boot.
repackaged by Spring Boot.
To run that application, use the `java -jar` command, as follows: To run that application, use the `java -jar` command, as follows:
...@@ -810,18 +739,12 @@ As before, to exit the application, press `ctrl-c`. ...@@ -810,18 +739,12 @@ As before, to exit the application, press `ctrl-c`.
[[getting-started-whats-next]] [[getting-started-whats-next]]
== What to Read Next == What to Read Next
Hopefully, this section provided some of the Spring Boot basics and got you on your way Hopefully, this section provided some of the Spring Boot basics and got you on your way to writing your own applications.
to writing your own applications. If you are a task-oriented type of developer, you might 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.
want to jump over to https://spring.io and check out some of the We also have Spring Boot-specific "`<<howto.adoc#howto, How-to>>`" reference documentation.
https://spring.io/guides/[getting started] guides that solve specific "`How do I do that
with Spring?`" problems. We also have Spring Boot-specific The https://github.com/{github-repo}[Spring Boot repository] also has a {github-code}/spring-boot-samples[bunch of samples] you can run.
"`<<howto.adoc#howto, How-to>>`" reference documentation. The samples are independent of the rest of the code (that is, you do not need to build the rest to run or use the samples).
The https://github.com/{github-repo}[Spring Boot repository] also has a Otherwise, the next logical step is to read _<<using-spring-boot.adoc#using-boot>>_.
{github-code}/spring-boot-samples[bunch of samples] you can run. The samples are If you are really impatient, you could also jump ahead and read about _<<spring-boot-features.adoc#boot-features, Spring Boot features>>_.
independent of the rest of the code (that is, you do not need to build the rest to run or
use the samples).
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>>_.
This source diff could not be displayed because it is too large. You can view the blob instead.
<productname>Spring Boot</productname> <productname>Spring Boot</productname>
<releaseinfo>{spring-boot-version}</releaseinfo> <releaseinfo>{spring-boot-version}</releaseinfo>
<copyright> <copyright>
<year>2012-2018</year> <year>2012-2019</year>
</copyright> </copyright>
<legalnotice> <legalnotice>
<para> <para>
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -3,28 +3,24 @@ ...@@ -3,28 +3,24 @@
[partintro] [partintro]
-- --
The Spring Boot CLI is a command line tool that you can use if you want to quickly develop The Spring Boot CLI is a command line tool that you can use if you want to quickly develop a Spring application.
a Spring application. It lets you run Groovy scripts, which means that you have a familiar It lets you run Groovy scripts, which means that you have a familiar Java-like syntax without so much boilerplate code.
Java-like syntax without so much boilerplate code. You can also bootstrap a new project or You can also bootstrap a new project or write your own command for it.
write your own command for it.
-- --
[[cli-installation]] [[cli-installation]]
== Installing the CLI == Installing the CLI
The Spring Boot CLI (Command-Line Interface) can be installed manually by using SDKMAN! 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.
(the SDK Manager) or by using Homebrew or MacPorts if you are an OSX user. See See _<<getting-started.adoc#getting-started-installing-the-cli>>_ in the "`Getting started`" section for comprehensive installation instructions.
_<<getting-started.adoc#getting-started-installing-the-cli>>_ in the "`Getting started`"
section for comprehensive installation instructions.
[[cli-using-the-cli]] [[cli-using-the-cli]]
== Using the CLI == Using the CLI
Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at the command line.
the command line. If you run `spring` without any arguments, a simple help screen is If you run `spring` without any arguments, a simple help screen is displayed, as follows:
displayed, as follows:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -40,8 +36,7 @@ displayed, as follows: ...@@ -40,8 +36,7 @@ displayed, as follows:
_... more command help is shown here_ _... more command help is shown here_
---- ----
You can type `spring help` to get more details about any of the supported commands, as You can type `spring help` to get more details about any of the supported commands, as shown in the following example:
shown in the following example:
[indent=0] [indent=0]
---- ----
...@@ -65,8 +60,7 @@ shown in the following example: ...@@ -65,8 +60,7 @@ shown in the following example:
--watch Watch the specified file for changes --watch Watch the specified file for changes
---- ----
The `version` command provides a quick way to check which version of Spring Boot you are The `version` command provides a quick way to check which version of Spring Boot you are using, as follows:
using, as follows:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -78,8 +72,8 @@ using, as follows: ...@@ -78,8 +72,8 @@ using, as follows:
[[cli-run]] [[cli-run]]
=== Running Applications with the CLI === Running Applications with the CLI
You can compile and run Groovy source code by using the `run` command. The Spring Boot CLI You can compile and run Groovy source code by using the `run` command.
is completely self-contained, so you do not need any external Groovy installation. 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: The following example shows a "`hello world`" web application written in Groovy:
...@@ -104,122 +98,108 @@ To compile and run the application, type the following command: ...@@ -104,122 +98,108 @@ To compile and run the application, type the following command:
$ spring run hello.groovy $ spring run hello.groovy
---- ----
To pass command-line arguments to the application, use `--` to separate the commands To pass command-line arguments to the application, use `--` to separate the commands from the "`spring`" command arguments, as shown in the following example:
from the "`spring`" command arguments, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ spring run hello.groovy -- --server.port=9000 $ spring run hello.groovy -- --server.port=9000
---- ----
To set JVM command line arguments, you can use the `JAVA_OPTS` environment variable, as To set JVM command line arguments, you can use the `JAVA_OPTS` environment variable, as shown in the following example:
shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ JAVA_OPTS=-Xmx1024m spring run hello.groovy $ JAVA_OPTS=-Xmx1024m spring run hello.groovy
---- ----
NOTE: When setting `JAVA_OPTS` on Microsoft Windows, make sure to quote the entire NOTE: When setting `JAVA_OPTS` on Microsoft Windows, make sure to quote the entire instruction, such as `set "JAVA_OPTS=-Xms256m -Xmx2048m"`.
instruction, such as `set "JAVA_OPTS=-Xms256m -Xmx2048m"`. Doing so ensures the values Doing so ensures the values are properly passed to the process.
are properly passed to the process.
[[cli-deduced-grab-annotations]] [[cli-deduced-grab-annotations]]
==== Deduced "`grab`" Dependencies ==== Deduced "`grab`" Dependencies
Standard Groovy includes a `@Grab` annotation, which lets you declare dependencies on Standard Groovy includes a `@Grab` annotation, which lets you declare dependencies on third-party libraries.
third-party libraries. This useful technique lets Groovy download jars in the same way as 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.
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`" Spring Boot extends this technique further and tries to deduce which libraries to "`grab`" based on your code.
based on your code. For example, since the `WebApplication` code shown previously uses For example, since the `WebApplication` code shown previously uses `@RestController` annotations, Spring Boot grabs "Tomcat" and "Spring MVC".
`@RestController` annotations, Spring Boot grabs "Tomcat" and "Spring MVC".
The following items are used as "`grab hints`": The following items are used as "`grab hints`":
|=== |===
| Items | Grabs | Items | Grabs
|`JdbcTemplate`, `NamedParameterJdbcTemplate`, `DataSource` | `JdbcTemplate`, `NamedParameterJdbcTemplate`, `DataSource`
|JDBC Application. | JDBC Application.
|`@EnableJms` | `@EnableJms`
|JMS Application. | JMS Application.
|`@EnableCaching` | `@EnableCaching`
|Caching abstraction. | Caching abstraction.
|`@Test` | `@Test`
|JUnit. | JUnit.
|`@EnableRabbit` | `@EnableRabbit`
|RabbitMQ. | RabbitMQ.
|extends `Specification` | extends `Specification`
|Spock test. | Spock test.
|`@EnableBatchProcessing` | `@EnableBatchProcessing`
|Spring Batch. | Spring Batch.
|`@MessageEndpoint` `@EnableIntegration` | `@MessageEndpoint` `@EnableIntegration`
|Spring Integration. | Spring Integration.
|`@Controller` `@RestController` `@EnableWebMvc` | `@Controller` `@RestController` `@EnableWebMvc`
|Spring MVC + Embedded Tomcat. | Spring MVC + Embedded Tomcat.
|`@EnableWebSecurity` | `@EnableWebSecurity`
|Spring Security. | Spring Security.
|`@EnableTransactionManagement` | `@EnableTransactionManagement`
|Spring Transaction Management. | Spring Transaction Management.
|=== |===
TIP: See subclasses of TIP: See subclasses of {sc-spring-boot-cli}/compiler/CompilerAutoConfiguration.{sc-ext}[`CompilerAutoConfiguration`] in the Spring Boot CLI source code to understand exactly how customizations are applied.
{sc-spring-boot-cli}/compiler/CompilerAutoConfiguration.{sc-ext}[`CompilerAutoConfiguration`]
in the Spring Boot CLI source code to understand exactly how customizations are applied.
[[cli-default-grab-deduced-coordinates]] [[cli-default-grab-deduced-coordinates]]
==== Deduced "`grab`" Coordinates ==== Deduced "`grab`" Coordinates
Spring Boot extends Groovy's standard `@Grab` support by letting you specify a dependency Spring Boot extends Groovy's standard `@Grab` support by letting you specify a dependency without a group or version (for example, `@Grab('freemarker')`).
without a group or version (for example, `@Grab('freemarker')`). Doing so consults Spring Doing so consults Spring Boot's default dependency metadata to deduce the artifact's group and version.
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 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.
when you move to a new version of the CLI, putting you in control of when the versions of A table showing the dependencies and their versions that are included in the default metadata can be found in the <<appendix-dependency-versions, appendix>>.
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,
appendix>>.
[[cli-default-import-statements]] [[cli-default-import-statements]]
==== Default Import Statements ==== Default Import Statements
To help reduce the size of your Groovy code, several `import` statements are automatically To help reduce the size of your Groovy code, several `import` statements are automatically included.
included. Notice how the preceding example refers to `@Component`, `@RestController`, and Notice how the preceding example refers to `@Component`, `@RestController`, and `@RequestMapping` without needing to use fully-qualified names or `import` statements.
`@RequestMapping` without needing to use fully-qualified names or `import` statements.
TIP: Many Spring annotations work without using `import` statements. Try running your TIP: Many Spring annotations work without using `import` statements.
application to see what fails before adding imports. Try running your application to see what fails before adding imports.
[[cli-automatic-main-method]] [[cli-automatic-main-method]]
==== Automatic Main Method ==== Automatic Main Method
Unlike the equivalent Java application, you do not need to include a Unlike the equivalent Java application, you do not need to include a `public static void main(String[] args)` method with your `Groovy` scripts.
`public static void main(String[] args)` method with your `Groovy` scripts. A A `SpringApplication` is automatically created, with your compiled code acting as the `source`.
`SpringApplication` is automatically created, with your compiled code acting as the
`source`.
[[cli-default-grab-deduced-coordinates-custom-dependency-management]] [[cli-default-grab-deduced-coordinates-custom-dependency-management]]
==== Custom Dependency Management ==== Custom Dependency Management
By default, the CLI uses the dependency management declared in `spring-boot-dependencies` By default, the CLI uses the dependency management declared in `spring-boot-dependencies` when resolving `@Grab` dependencies.
when resolving `@Grab` dependencies. Additional dependency management, which overrides Additional dependency management, which overrides the default dependency management, can be configured by using the `@DependencyManagementBom` annotation.
the default dependency management, can be configured by using the The annotation's value should specify the coordinates (`groupId:artifactId:version`) of one or more Maven BOMs.
`@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: For example, consider the following declaration:
...@@ -228,11 +208,9 @@ For example, consider the following declaration: ...@@ -228,11 +208,9 @@ For example, consider the following declaration:
@DependencyManagementBom("com.example.custom-bom:1.0.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 The preceding declaration picks up `custom-bom-1.0.0.pom` in a Maven repository under `com/example/custom-versions/1.0.0/`.
`com/example/custom-versions/1.0.0/`.
When you specify multiple BOMs, they are applied in the order in which you declare them, When you specify multiple BOMs, they are applied in the order in which you declare them, as shown in the following example:
as shown in the following example:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -240,15 +218,11 @@ as shown in the following example: ...@@ -240,15 +218,11 @@ as shown in the following example:
"com.example.another-bom:1.0.0"]) "com.example.another-bom:1.0.0"])
---- ----
The preceding example indicates that the dependency management in `another-bom` overrides The preceding example indicates that the dependency management in `another-bom` overrides the dependency management in `custom-bom`.
the dependency management in `custom-bom`.
You can use `@DependencyManagementBom` anywhere that you can use `@Grab`. However, to You can use `@DependencyManagementBom` anywhere that you can use `@Grab`.
ensure consistent ordering of the dependency management, you can use However, to ensure consistent ordering of the dependency management, you can use `@DependencyManagementBom` at most once in your application.
`@DependencyManagementBom` at most once in your application. A useful source of dependency A useful source of dependency management (which is a superset of Spring Boot's dependency management) is the https://platform.spring.io/[Spring IO Platform], which you might include with the following line:
management (which is a superset of Spring Boot's dependency management) is the
https://platform.spring.io/[Spring IO Platform], which you might include with the following
line:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -258,8 +232,8 @@ line: ...@@ -258,8 +232,8 @@ line:
[[cli-multiple-source-files]] [[cli-multiple-source-files]]
=== Applications with Multiple Source Files === Applications with Multiple Source Files
You can use "`shell globbing`" with all commands that accept file input. Doing so lets You can use "`shell globbing`" with all commands that accept file input.
you use multiple files from a single directory, as shown in the following example: Doing so lets you use multiple files from a single directory, as shown in the following example:
[indent=0] [indent=0]
---- ----
...@@ -270,20 +244,18 @@ you use multiple files from a single directory, as shown in the following exampl ...@@ -270,20 +244,18 @@ you use multiple files from a single directory, as shown in the following exampl
[[cli-jar]] [[cli-jar]]
=== Packaging Your Application === Packaging Your Application
You can use the `jar` command to package your application into a self-contained executable You can use the `jar` command to package your application into a self-contained executable jar file, as shown in the following example:
jar file, as shown in the following example:
[indent=0] [indent=0]
---- ----
$ spring jar my-app.jar *.groovy $ spring jar my-app.jar *.groovy
---- ----
The resulting jar contains the classes produced by compiling the application and all of 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 application's dependencies so that it can then be run by using `java -jar`. The jar The jar file also contains entries from the application's classpath.
file also contains entries from the application's classpath. You can add and remove You can add and remove explicit paths to the jar by using `--include` and `--exclude`.
explicit paths to the jar by using `--include` and `--exclude`. Both are comma-separated, Both are comma-separated, and both accept prefixes, in the form of "`+`" and "`-`", to signify that they should be removed from the defaults.
and both accept prefixes, in the form of "`+`" and "`-`", to signify that they should be The default includes are as follows:
removed from the defaults. The default includes are as follows:
[indent=0] [indent=0]
---- ----
...@@ -303,8 +275,7 @@ Type `spring help jar` on the command line for more information. ...@@ -303,8 +275,7 @@ Type `spring help jar` on the command line for more information.
[[cli-init]] [[cli-init]]
=== Initialize a New Project === Initialize a New Project
The `init` command lets you create a new project by using https://start.spring.io without 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:
leaving the shell, as shown in the following example:
[indent=0] [indent=0]
---- ----
...@@ -313,9 +284,8 @@ leaving the shell, as shown in the following example: ...@@ -313,9 +284,8 @@ leaving the shell, as shown in the following example:
Project extracted to '/Users/developer/example/my-project' Project extracted to '/Users/developer/example/my-project'
---- ----
The preceding example creates a `my-project` directory with a Maven-based project that 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`.
uses `spring-boot-starter-web` and `spring-boot-starter-data-jpa`. You can list the You can list the capabilities of the service by using the `--list` flag, as shown in the following example:
capabilities of the service by using the `--list` flag, as shown in the following example:
[indent=0] [indent=0]
---- ----
...@@ -342,9 +312,9 @@ capabilities of the service by using the `--list` flag, as shown in the followin ...@@ -342,9 +312,9 @@ capabilities of the service by using the `--list` flag, as shown in the followin
... ...
---- ----
The `init` command supports many options. See the `help` output for more details. For The `init` command supports many options.
instance, the following command creates a Gradle project that uses Java 8 and `war` See the `help` output for more details.
packaging: For instance, the following command creates a Gradle project that uses Java 8 and `war` packaging:
[indent=0] [indent=0]
---- ----
...@@ -357,9 +327,8 @@ packaging: ...@@ -357,9 +327,8 @@ packaging:
[[cli-shell]] [[cli-shell]]
=== Using the Embedded Shell === Using the Embedded Shell
Spring Boot includes command-line completion scripts for the BASH and zsh shells. If you Spring Boot includes command-line completion scripts for the BASH and zsh shells.
do not use either of these shells (perhaps you are a Windows user), you can use the 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:
`shell` command to launch an integrated shell, as shown in the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -376,40 +345,34 @@ From inside the embedded shell, you can run other commands directly: ...@@ -376,40 +345,34 @@ From inside the embedded shell, you can run other commands directly:
Spring CLI v{spring-boot-version} Spring CLI v{spring-boot-version}
---- ----
The embedded shell supports ANSI color output as well as `tab` completion. If you need to The embedded shell supports ANSI color output as well as `tab` completion.
run a native command, you can use the `!` prefix. To exit the embedded shell, press If you need to run a native command, you can use the `!` prefix.
`ctrl-c`. To exit the embedded shell, press `ctrl-c`.
[[cli-install-uninstall]] [[cli-install-uninstall]]
=== Adding Extensions to the CLI === Adding Extensions to the CLI
You can add extensions to the CLI by using the `install` command. The command takes one You can add extensions to the CLI by using the `install` command.
or more sets of artifact coordinates in the format `group:artifact:version`, as shown in The command takes one or more sets of artifact coordinates in the format `group:artifact:version`, as shown in the following example:
the following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE $ 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 In addition to installing the artifacts identified by the coordinates you supply, all of the artifacts' dependencies are also installed.
the artifacts' dependencies are also installed.
To uninstall a dependency, use the `uninstall` command. As with the `install` command, it 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:
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"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE $ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE
---- ----
It uninstalls the artifacts identified by the coordinates you supply and their It uninstalls the artifacts identified by the coordinates you supply and their dependencies.
dependencies.
To uninstall all additional dependencies, you can use the `--all` option, as shown in the To uninstall all additional dependencies, you can use the `--all` option, as shown in the following example:
following example:
[indent=0,subs="verbatim,quotes,attributes"] [indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -420,10 +383,8 @@ following example: ...@@ -420,10 +383,8 @@ following example:
[[cli-groovy-beans-dsl]] [[cli-groovy-beans-dsl]]
== Developing Applications with the Groovy Beans DSL == Developing Applications with the Groovy Beans DSL
Spring Framework 4.0 has native support for a `beans{}` "`DSL`" (borrowed from 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.
https://grails.org/[Grails]), and you can embed bean definitions in your Groovy application This is sometimes a good way to include external features like middleware declarations, as shown in the following example:
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] [source,groovy,indent=0]
---- ----
...@@ -449,16 +410,15 @@ features like middleware declarations, as shown in the following example: ...@@ -449,16 +410,15 @@ features like middleware declarations, as shown in the following example:
} }
---- ----
You can mix class declarations with `beans{}` in the same file as long as they stay at 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.
the top level, or, if you prefer, you can put the beans DSL in a separate file.
[[cli-maven-settings]] [[cli-maven-settings]]
== Configuring the CLI with `settings.xml` == Configuring the CLI with `settings.xml`
The Spring Boot CLI uses Aether, Maven's dependency resolution engine, to resolve The Spring Boot CLI uses Aether, Maven's dependency resolution engine, to resolve dependencies.
dependencies. The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` to configure Aether.
to configure Aether. The following configuration settings are honored by the CLI: The following configuration settings are honored by the CLI:
* Offline * Offline
* Mirrors * Mirrors
...@@ -469,18 +429,14 @@ to configure Aether. The following configuration settings are honored by the CLI ...@@ -469,18 +429,14 @@ to configure Aether. The following configuration settings are honored by the CLI
** Repositories ** Repositories
* Active profiles * Active profiles
See https://maven.apache.org/settings.html[Maven's settings documentation] for further See https://maven.apache.org/settings.html[Maven's settings documentation] for further information.
information.
[[cli-whats-next]] [[cli-whats-next]]
== What to Read Next == What to Read Next
There are some {github-code}/spring-boot-project/spring-boot-cli/samples[sample groovy There are some {github-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.
scripts] available from the GitHub repository that you can use to try out the Spring Boot There is also extensive Javadoc throughout the {sc-spring-boot-cli}[source code].
CLI. There is also extensive Javadoc throughout the {sc-spring-boot-cli}[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`".
If you find that you reach the limit of the CLI tool, you probably want to look at 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.
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.
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -3,83 +3,61 @@ ...@@ -3,83 +3,61 @@
[partintro] [partintro]
-- --
This section goes into more detail about how you should use Spring Boot. It covers topics This section goes into more detail about how you should use Spring Boot.
such as build systems, auto-configuration, and how to run your applications. We also It covers topics such as build systems, auto-configuration, and how to run your applications.
cover some Spring Boot best practices. Although there is nothing particularly special We also cover some Spring Boot best practices.
about Spring Boot (it is just another library that you can consume), there are a few Although there is nothing particularly special about Spring Boot (it is just another library that you can consume), there are a few recommendations that, when followed, make your development process a little easier.
recommendations that, when followed, make your development process a little easier.
If you are starting out with Spring Boot, you should probably read the _<<getting-started.adoc#getting-started, Getting Started>>_ guide before diving into this section.
If you are starting out with Spring Boot, you should probably read the
_<<getting-started.adoc#getting-started, Getting Started>>_ guide before diving into this
section.
-- --
[[using-boot-build-systems]] [[using-boot-build-systems]]
== Build Systems == Build Systems
It is strongly recommended that you choose a build system that supports It is strongly recommended that you choose a build system that supports <<using-boot-dependency-management,_dependency management_>> and that can consume artifacts published to the "`Maven Central`" repository.
<<using-boot-dependency-management,_dependency management_>> and that can consume We would recommend that you choose Maven or Gradle.
artifacts published to the "`Maven Central`" repository. We would recommend that you It is possible to get Spring Boot to work with other build systems (Ant, for example), but they are not particularly well supported.
choose Maven or Gradle. It is possible to get Spring Boot to work with other build
systems (Ant, for example), but they are not particularly well supported.
[[using-boot-dependency-management]] [[using-boot-dependency-management]]
=== Dependency Management === Dependency Management
Each release of Spring Boot provides a curated list of dependencies that it supports. In Each release of Spring Boot provides a curated list of dependencies that it supports.
practice, you do not need to provide a version for any of these dependencies in your In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you.
build configuration, as Spring Boot manages that for you. When you upgrade Spring When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way.
Boot itself, these dependencies are upgraded as well in a consistent way.
NOTE: You can still specify a version and override Spring Boot's recommendations if you NOTE: You can still specify a version and override Spring Boot's recommendations if you need to do so.
need to do so.
The curated list contains all the spring modules that you can use with Spring Boot as The curated list contains all the spring modules that you can use with Spring Boot as well as a refined list of third party libraries.
well as a refined list of third party libraries. The list is available as a standard The list is available as a standard <<using-boot-maven-without-a-parent,Bills of Materials (`spring-boot-dependencies`)>> that can be used with both <<using-boot-maven-parent-pom,Maven>> and <<using-boot-gradle,Gradle>>.
<<using-boot-maven-without-a-parent,Bills of Materials (`spring-boot-dependencies`)>>
that can be used with both <<using-boot-maven-parent-pom,Maven>> and
<<using-boot-gradle,Gradle>>.
WARNING: Each release of Spring Boot is associated with a base version of the Spring WARNING: Each release of Spring Boot is associated with a base version of the Spring Framework. We **highly** recommend that you not specify its version.
Framework. We **highly** recommend that you not specify its version.
[[using-boot-maven]] [[using-boot-maven]]
=== Maven === Maven
Maven users can inherit from the `spring-boot-starter-parent` project to obtain sensible Maven users can inherit from the `spring-boot-starter-parent` project to obtain sensible defaults.
defaults. The parent project provides the following features: The parent project provides the following features:
* Java 1.8 as the default compiler level. * Java 1.8 as the default compiler level.
* UTF-8 source encoding. * UTF-8 source encoding.
* A <<using-boot-dependency-management,Dependency Management section>>, inherited from * A <<using-boot-dependency-management,Dependency Management section>>, inherited from the spring-boot-dependencies pom, that manages the versions of common dependencies.
the spring-boot-dependencies pom, that manages the versions of common dependencies. This This dependency management lets you omit <version> tags for those dependencies when used in your own pom.
dependency management lets you omit <version> tags for those dependencies when used in * An execution of the {spring-boot-maven-plugin-site}/repackage-mojo.html[`repackage` goal] with a `repackage` execution id.
your own pom. * Sensible https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html[resource filtering].
* An execution of the {spring-boot-maven-plugin-site}/repackage-mojo.html[`repackage` * Sensible plugin configuration (https://www.mojohaus.org/exec-maven-plugin/[exec plugin], https://github.com/ktoso/maven-git-commit-id-plugin[Git commit ID], and https://maven.apache.org/plugins/maven-shade-plugin/[shade]).
goal] with a `repackage` execution id. * Sensible resource filtering for `application.properties` and `application.yml` including profile-specific files (for example, `application-dev.properties` and `application-dev.yml`)
* Sensible
https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html[resource Note that, since the `application.properties` and `application.yml` files accept Spring style placeholders (`${...}`), the Maven filtering is changed to use `@..@` placeholders.
filtering].
* Sensible plugin configuration (https://www.mojohaus.org/exec-maven-plugin/[exec plugin],
https://github.com/ktoso/maven-git-commit-id-plugin[Git commit ID], and
https://maven.apache.org/plugins/maven-shade-plugin/[shade]).
* Sensible resource filtering for `application.properties` and `application.yml`
including profile-specific files (for example, `application-dev.properties` and
`application-dev.yml`)
Note that, since the `application.properties` and `application.yml` files accept Spring
style placeholders (`${...}`), the Maven filtering is changed to use `@..@` placeholders.
(You can override that by setting a Maven property called `resource.delimiter`.) (You can override that by setting a Maven property called `resource.delimiter`.)
[[using-boot-maven-parent-pom]] [[using-boot-maven-parent-pom]]
==== Inheriting the Starter Parent ==== Inheriting the Starter Parent
To configure your project to inherit from the `spring-boot-starter-parent`, set the To configure your project to inherit from the `spring-boot-starter-parent`, set the `parent` as follows:
`parent` as follows:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -94,9 +72,8 @@ To configure your project to inherit from the `spring-boot-starter-parent`, set ...@@ -94,9 +72,8 @@ To configure your project to inherit from the `spring-boot-starter-parent`, set
NOTE: You should need to specify only the Spring Boot version number on this dependency. NOTE: You should need to specify only the Spring Boot version number on this dependency.
If you import additional starters, you can safely omit the version number. If you import additional starters, you can safely omit the version number.
With that setup, you can also override individual dependencies by overriding a property With that setup, you can also override individual dependencies by overriding a property in your own project.
in your own project. For instance, to upgrade to another Spring Data release train, you For instance, to upgrade to another Spring Data release train, you would add the following to your `pom.xml`:
would add the following to your `pom.xml`:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -105,21 +82,16 @@ would add the following to your `pom.xml`: ...@@ -105,21 +82,16 @@ would add the following to your `pom.xml`:
</properties> </properties>
---- ----
TIP: Check the TIP: Check the {github-code}/spring-boot-project/spring-boot-dependencies/pom.xml[`spring-boot-dependencies` pom] for a list of supported properties.
{github-code}/spring-boot-project/spring-boot-dependencies/pom.xml[`spring-boot-dependencies` pom]
for a list of supported properties.
[[using-boot-maven-without-a-parent]] [[using-boot-maven-without-a-parent]]
==== Using Spring Boot without the Parent POM ==== Using Spring Boot without the Parent POM
Not everyone likes inheriting from the `spring-boot-starter-parent` POM. You may have Not everyone likes inheriting from the `spring-boot-starter-parent` POM.
your own corporate standard parent that you need to use or you may prefer to explicitly You may have your own corporate standard parent that you need to use or you may prefer to explicitly declare all your Maven configuration.
declare all your Maven configuration.
If you do not want to use the `spring-boot-starter-parent`, you can still keep the If you do not want to use the `spring-boot-starter-parent`, you can still keep the benefit of the dependency management (but not the plugin management) by using a `scope=import` dependency, as follows:
benefit of the dependency management (but not the plugin management) by using a
`scope=import` dependency, as follows:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -137,11 +109,9 @@ benefit of the dependency management (but not the plugin management) by using a ...@@ -137,11 +109,9 @@ benefit of the dependency management (but not the plugin management) by using a
</dependencyManagement> </dependencyManagement>
---- ----
The preceding sample setup does not let you override individual dependencies by using a The preceding sample setup does not let you override individual dependencies by using a property, as explained above.
property, as explained above. To achieve the same result, you need to add an entry in the To achieve the same result, you need to add an entry in the `dependencyManagement` of your project **before** the `spring-boot-dependencies` entry.
`dependencyManagement` of your project **before** the `spring-boot-dependencies` entry. For instance, to upgrade to another Spring Data release train, you could add the following element to your `pom.xml`:
For instance, to upgrade to another Spring Data release train, you could add the
following element to your `pom.xml`:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -166,16 +136,14 @@ following element to your `pom.xml`: ...@@ -166,16 +136,14 @@ following element to your `pom.xml`:
</dependencyManagement> </dependencyManagement>
---- ----
NOTE: In the preceding example, we specify a _BOM_, but any dependency type can be NOTE: In the preceding example, we specify a _BOM_, but any dependency type can be overridden in the same way.
overridden in the same way.
[[using-boot-maven-plugin]] [[using-boot-maven-plugin]]
==== Using the Spring Boot Maven Plugin ==== Using the Spring Boot Maven Plugin
Spring Boot includes a <<build-tool-plugins.adoc#build-tool-plugins-maven-plugin, Maven Spring Boot includes a <<build-tool-plugins.adoc#build-tool-plugins-maven-plugin, Maven plugin>> that can package the project as an executable jar.
plugin>> that can package the project as an executable jar. Add the plugin to your Add the plugin to your `<plugins>` section if you want to use it, as shown in the following example:
`<plugins>` section if you want to use it, as shown in the following example:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -190,28 +158,25 @@ plugin>> that can package the project as an executable jar. Add the plugin to yo ...@@ -190,28 +158,25 @@ plugin>> that can package the project as an executable jar. Add the plugin to yo
---- ----
NOTE: If you use the Spring Boot starter parent pom, you need to add only the plugin. NOTE: If you use the Spring Boot starter parent pom, you need to add only the plugin.
There is no need to configure it unless you want to change the settings defined in the There is no need to configure it unless you want to change the settings defined in the parent.
parent.
[[using-boot-gradle]] [[using-boot-gradle]]
=== Gradle === Gradle
To learn about using Spring Boot with Gradle, please refer to the documentation for To learn about using Spring Boot with Gradle, please refer to the documentation for Spring Boot's Gradle plugin:
Spring Boot's Gradle plugin:
* Reference ({spring-boot-gradle-plugin}/reference/html[HTML] and * Reference ({spring-boot-gradle-plugin}/reference/html[HTML] and {spring-boot-gradle-plugin}/reference/pdf/spring-boot-gradle-plugin-reference.pdf[PDF])
{spring-boot-gradle-plugin}/reference/pdf/spring-boot-gradle-plugin-reference.pdf[PDF])
* {spring-boot-gradle-plugin}/api[API] * {spring-boot-gradle-plugin}/api[API]
[[using-boot-ant]] [[using-boot-ant]]
=== Ant === Ant
It is possible to build a Spring Boot project using Apache Ant+Ivy. The It is possible to build a Spring Boot project using Apache Ant+Ivy.
`spring-boot-antlib` "`AntLib`" module is also available to help Ant create executable The `spring-boot-antlib` "`AntLib`" module is also available to help Ant create executable jars.
jars.
To declare dependencies, a typical `ivy.xml` file looks something like the following To declare dependencies, a typical `ivy.xml` file looks something like the following example:
example:
[source,xml,indent=0] [source,xml,indent=0]
---- ----
...@@ -267,95 +232,72 @@ A typical `build.xml` looks like the following example: ...@@ -267,95 +232,72 @@ A typical `build.xml` looks like the following example:
</project> </project>
---- ----
TIP: If you do not want to use the `spring-boot-antlib` module, see the TIP: If you do not want to use the `spring-boot-antlib` module, see the _<<howto.adoc#howto-build-an-executable-archive-with-ant>>_ "`How-to`" .
_<<howto.adoc#howto-build-an-executable-archive-with-ant>>_ "`How-to`" .
[[using-boot-starter]] [[using-boot-starter]]
=== Starters === Starters
Starters are a set of convenient dependency descriptors that you can include in your Starters are a set of convenient dependency descriptors that you can include in your application.
application. You get a one-stop shop for all the Spring and related technologies that you You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors.
need without having to hunt through sample code and copy-paste loads of dependency For example, if you want to get started using Spring and JPA for database access, include the `spring-boot-starter-data-jpa` dependency in your project.
descriptors. For example, if you want to get started using Spring and JPA for database
access, include the `spring-boot-starter-data-jpa` dependency in your project.
The starters contain a lot of the dependencies that you need to get a project up and The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
running quickly and with a consistent, supported set of managed transitive dependencies.
.What's in a name .What's in a name
**** ****
All **official** starters follow a similar naming pattern; `+spring-boot-starter-*+`, All **official** starters follow a similar naming pattern; `+spring-boot-starter-*+`, where `+*+` is a particular type of application.
where `+*+` is a particular type of application. This naming structure is intended to This naming structure is intended to help when you need to find a starter.
help when you need to find a starter. The Maven integration in many IDEs lets you The Maven integration in many IDEs lets you search dependencies by name.
search dependencies by name. For example, with the appropriate Eclipse or STS plugin For example, with the appropriate Eclipse or STS plugin installed, you can press `ctrl-space` in the POM editor and type "`spring-boot-starter`" for a complete list.
installed, you can press `ctrl-space` in the POM editor and type
"`spring-boot-starter`" for a complete list. As explained in the "`<<spring-boot-features#boot-features-custom-starter,Creating Your Own Starter>>`" section, third party starters should not start with `spring-boot`, as it is reserved for official Spring Boot artifacts.
Rather, a third-party starter typically starts with the name of the project.
As explained in the "`<<spring-boot-features#boot-features-custom-starter,Creating Your For example, a third-party starter project called `thirdpartyproject` would typically be named `thirdpartyproject-spring-boot-starter`.
Own Starter>>`" section, third party starters should not start with `spring-boot`, as it
is reserved for official Spring Boot artifacts. Rather, a third-party starter typically
starts with the name of the project. For example, a third-party starter project called
`thirdpartyproject` would typically be named `thirdpartyproject-spring-boot-starter`.
**** ****
The following application starters are provided by Spring Boot under the The following application starters are provided by Spring Boot under the `org.springframework.boot` group:
`org.springframework.boot` group:
.Spring Boot application starters .Spring Boot application starters
include::../../../target/generated-resources/application-starters.adoc[] include::../../../target/generated-resources/application-starters.adoc[]
In addition to the application starters, the following starters can be used to add In addition to the application starters, the following starters can be used to add _<<production-ready-features.adoc#production-ready, production ready>>_ features:
_<<production-ready-features.adoc#production-ready, production ready>>_ features:
.Spring Boot production starters .Spring Boot production starters
include::../../../target/generated-resources/production-starters.adoc[] include::../../../target/generated-resources/production-starters.adoc[]
Finally, Spring Boot also includes the following starters that can be used if you want to Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets:
exclude or swap specific technical facets:
.Spring Boot technical starters .Spring Boot technical starters
include::../../../target/generated-resources/technical-starters.adoc[] include::../../../target/generated-resources/technical-starters.adoc[]
TIP: For a list of additional community contributed starters, see the TIP: For a list of additional community contributed starters, see the {github-master-code}/spring-boot-project/spring-boot-starters/README.adoc[README file] in the `spring-boot-starters` module on GitHub.
{github-master-code}/spring-boot-project/spring-boot-starters/README.adoc[README file] in
the `spring-boot-starters` module on GitHub.
[[using-boot-structuring-your-code]] [[using-boot-structuring-your-code]]
== Structuring Your Code == Structuring Your Code
Spring Boot does not require any specific code layout to work. However, there are some Spring Boot does not require any specific code layout to work. However, there are some best practices that help.
best practices that help.
[[using-boot-using-the-default-package]] [[using-boot-using-the-default-package]]
=== Using the "`default`" Package === Using the "`default`" Package
When a class does not include a `package` declaration, it is considered to be in the When a class does not include a `package` declaration, it is considered to be in the "`default package`".
"`default package`". The use of the "`default package`" is generally discouraged and The use of the "`default package`" is generally discouraged and should be avoided.
should be avoided. It can cause particular problems for Spring Boot applications that use It can cause particular problems for Spring Boot applications that use the `@ComponentScan`, `@EntityScan`, or `@SpringBootApplication` annotations, since every class from every jar is read.
the `@ComponentScan`, `@EntityScan`, or `@SpringBootApplication` annotations, since every
class from every jar is read.
TIP: We recommend that you follow Java's recommended package naming conventions and use a TIP: We recommend that you follow Java's recommended package naming conventions and use a reversed domain name (for example, `com.example.project`).
reversed domain name (for example, `com.example.project`).
[[using-boot-locating-the-main-class]] [[using-boot-locating-the-main-class]]
=== Locating the Main Application Class === Locating the Main Application Class
We generally recommend that you locate your main application class in a root package We generally recommend that you locate your main application class in a root package above other classes.
above other classes. The <<using-boot-using-springbootapplication-annotation, The <<using-boot-using-springbootapplication-annotation, `@SpringBootApplication` annotation>> is often placed on your main class, and it implicitly defines a base "`search package`" for certain items.
`@SpringBootApplication` annotation>> is often placed on your main class, and it For example, if you are writing a JPA application, the package of the `@SpringBootApplication` annotated class is used to search for `@Entity` items. Using a root package also allows component scan to apply only on your project.
implicitly defines a base "`search package`" for certain items. For example, if you are
writing a JPA application, the package of the `@SpringBootApplication` annotated class TIP: If you don't want to use `@SpringBootApplication`, the `@EnableAutoConfiguration` and `@ComponentScan` annotations that it imports defines that behavior so you can also use that instead.
is used to search for `@Entity` items. Using a root package also allows component
scan to apply only on your project.
TIP: If you don't want to use `@SpringBootApplication`, the `@EnableAutoConfiguration`
and `@ComponentScan` annotations that it imports defines that behaviour so you can also
use that instead.
The following listing shows a typical layout: The following listing shows a typical layout:
...@@ -379,8 +321,7 @@ The following listing shows a typical layout: ...@@ -379,8 +321,7 @@ The following listing shows a typical layout:
+- OrderRepository.java +- OrderRepository.java
---- ----
The `Application.java` file would declare the `main` method, along with the basic The `Application.java` file would declare the `main` method, along with the basic `@SpringBootApplication`, as follows:
`@SpringBootApplication`, as follows:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -403,67 +344,57 @@ The `Application.java` file would declare the `main` method, along with the basi ...@@ -403,67 +344,57 @@ The `Application.java` file would declare the `main` method, along with the basi
[[using-boot-configuration-classes]] [[using-boot-configuration-classes]]
== Configuration Classes == Configuration Classes
Spring Boot favors Java-based configuration. Although it is possible to use Spring Boot favors Java-based configuration.
`SpringApplication` with XML sources, we generally recommend that your primary source be Although it is possible to use `SpringApplication` with XML sources, we generally recommend that your primary source be a single `@Configuration` class.
a single `@Configuration` class. Usually the class that defines the `main` method is a Usually the class that defines the `main` method is a good candidate as the primary `@Configuration`.
good candidate as the primary `@Configuration`.
TIP: Many Spring configuration examples have been published on the Internet that use XML TIP: Many Spring configuration examples have been published on the Internet that use XML configuration.
configuration. If possible, always try to use the equivalent Java-based configuration. If possible, always try to use the equivalent Java-based configuration.
Searching for `+Enable*+` annotations can be a good starting point. Searching for `+Enable*+` annotations can be a good starting point.
[[using-boot-importing-configuration]] [[using-boot-importing-configuration]]
=== Importing Additional Configuration Classes === Importing Additional Configuration Classes
You need not put all your `@Configuration` into a single class. The `@Import` annotation You need not put all your `@Configuration` into a single class.
can be used to import additional configuration classes. Alternatively, you can use The `@Import` annotation can be used to import additional configuration classes.
`@ComponentScan` to automatically pick up all Spring components, including Alternatively, you can use `@ComponentScan` to automatically pick up all Spring components, including `@Configuration` classes.
`@Configuration` classes.
[[using-boot-importing-xml-configuration]] [[using-boot-importing-xml-configuration]]
=== Importing XML Configuration === Importing XML Configuration
If you absolutely must use XML based configuration, we recommend that you still start If you absolutely must use XML based configuration, we recommend that you still start with a `@Configuration` class.
with a `@Configuration` class. You can then use an `@ImportResource` annotation to load You can then use an `@ImportResource` annotation to load XML configuration files.
XML configuration files.
[[using-boot-auto-configuration]] [[using-boot-auto-configuration]]
== Auto-configuration == Auto-configuration
Spring Boot auto-configuration attempts to automatically configure your Spring Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.
application based on the jar dependencies that you have added. For example, if `HSQLDB` For example, if `HSQLDB` is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.
is on your classpath, and you have not manually configured any database connection beans,
then Spring Boot auto-configures an in-memory database.
You need to opt-in to auto-configuration by adding the `@EnableAutoConfiguration` or You need to opt-in to auto-configuration by adding the `@EnableAutoConfiguration` or `@SpringBootApplication` annotations to one of your `@Configuration` classes.
`@SpringBootApplication` annotations to one of your `@Configuration` classes.
TIP: You should only ever add one `@SpringBootApplication` or `@EnableAutoConfiguration` TIP: You should only ever add one `@SpringBootApplication` or `@EnableAutoConfiguration` annotation.
annotation. We generally recommend that you add one or the other to your primary We generally recommend that you add one or the other to your primary `@Configuration` class only.
`@Configuration` class only.
[[using-boot-replacing-auto-configuration]] [[using-boot-replacing-auto-configuration]]
=== Gradually Replacing Auto-configuration === Gradually Replacing Auto-configuration
Auto-configuration is non-invasive. At any point, you can start to define your own Auto-configuration is non-invasive.
configuration to replace specific parts of the auto-configuration. For example, if you At any point, you can start to define your own configuration to replace specific parts of the auto-configuration.
add your own `DataSource` bean, the default embedded database support backs away. For example, if you add your own `DataSource` bean, the default embedded database support backs away.
If you need to find out what auto-configuration is currently being applied, and why, If you need to find out what auto-configuration is currently being applied, and why, start your application with the `--debug` switch.
start your application with the `--debug` switch. Doing so enables debug logs for a Doing so enables debug logs for a selection of core loggers and logs a conditions report to the console.
selection of core loggers and logs a conditions report to the console.
[[using-boot-disabling-specific-auto-configuration]] [[using-boot-disabling-specific-auto-configuration]]
=== Disabling Specific Auto-configuration Classes === Disabling Specific Auto-configuration Classes
If you find that specific auto-configuration classes that you do not want are being If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of `@EnableAutoConfiguration` to disable them, as shown in the following example:
applied, you can use the exclude attribute of `@EnableAutoConfiguration` to disable them,
as shown in the following example:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -477,32 +408,25 @@ as shown in the following example: ...@@ -477,32 +408,25 @@ as shown in the following example:
} }
---- ----
If the class is not on the classpath, you can use the `excludeName` attribute of the If the class is not on the classpath, you can use the `excludeName` attribute of the annotation and specify the fully qualified name instead.
annotation and specify the fully qualified name instead. Finally, you can also control Finally, you can also control the list of auto-configuration classes to exclude by using the `spring.autoconfigure.exclude` property.
the list of auto-configuration classes to exclude by using the
`spring.autoconfigure.exclude` property.
TIP: You can define exclusions both at the annotation level and by using the property. TIP: You can define exclusions both at the annotation level and by using the property.
NOTE: Even though auto-configuration classes are `public`, the only aspect of the class NOTE: Even though auto-configuration classes are `public`, the only aspect of the class that is considered public API is the name of the class which can be used for disabling the auto-configuration.
that is considered public API is the name of the class which can be used for disabling the The actual contents of those classes, such as nested configuration classes or bean methods are for internal use only and we do not recommend using those directly.
auto-configuration. The actual contents of those classes, such as nested configuration classes
or bean methods are for internal use only and we do not recommend using those directly.
[[using-boot-spring-beans-and-dependency-injection]] [[using-boot-spring-beans-and-dependency-injection]]
== Spring Beans and Dependency Injection == Spring Beans and Dependency Injection
You are free to use any of the standard Spring Framework techniques to define your beans You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
and their injected dependencies. For simplicity, we often find that using For simplicity, we often find that using `@ComponentScan` (to find your beans) and using `@Autowired` (to do constructor injection) works well.
`@ComponentScan` (to find your beans) and using `@Autowired` (to do constructor
injection) works well.
If you structure your code as suggested above (locating your application class in a root If you structure your code as suggested above (locating your application class in a root package), you can add `@ComponentScan` without any arguments.
package), you can add `@ComponentScan` without any arguments. All of your application All of your application components (`@Component`, `@Service`, `@Repository`, `@Controller` etc.) are automatically registered as Spring Beans.
components (`@Component`, `@Service`, `@Repository`, `@Controller` etc.) are
automatically registered as Spring Beans.
The following example shows a `@Service` Bean that uses constructor injection to obtain a The following example shows a `@Service` Bean that uses constructor injection to obtain a required `RiskAssessor` bean:
required `RiskAssessor` bean:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -526,8 +450,7 @@ required `RiskAssessor` bean: ...@@ -526,8 +450,7 @@ required `RiskAssessor` bean:
} }
---- ----
If a bean has one constructor, you can omit the `@Autowired`, as shown in the following If a bean has one constructor, you can omit the `@Autowired`, as shown in the following example:
example:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -545,28 +468,20 @@ example: ...@@ -545,28 +468,20 @@ example:
} }
---- ----
TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as TIP: Notice how using constructor injection lets the `riskAssessor` field be marked as `final`, indicating that it cannot be subsequently changed.
`final`, indicating that it cannot be subsequently changed.
[[using-boot-using-springbootapplication-annotation]] [[using-boot-using-springbootapplication-annotation]]
== Using the @SpringBootApplication Annotation == Using the @SpringBootApplication Annotation
Many Spring Boot developers like their apps to use auto-configuration, component scan and Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class".
be able to define extra configuration on their "application class". A single A single `@SpringBootApplication` annotation can be used to enable those three features, that is:
`@SpringBootApplication` annotation can be used to enable those three features, that is:
* `@EnableAutoConfiguration`: enable <<using-boot-auto-configuration,Spring Boot's
auto-configuration mechanism>>
* `@ComponentScan`: enable `@Component` scan on the package where the application is
located (see <<using-boot-structuring-your-code,the best practices>>)
* `@Configuration`: allow to register extra beans in the context or import additional
configuration classes
The `@SpringBootApplication` annotation is equivalent to using `@Configuration`, * `@EnableAutoConfiguration`: enable <<using-boot-auto-configuration,Spring Boot's auto-configuration mechanism>>
`@EnableAutoConfiguration`, and `@ComponentScan` with their default attributes, as shown * `@ComponentScan`: enable `@Component` scan on the package where the application is located (see <<using-boot-structuring-your-code,the best practices>>)
in the following example: * `@Configuration`: allow to register extra beans in the context or import additional configuration classes
The `@SpringBootApplication` annotation is equivalent to using `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan` with their default attributes, as shown in the following example:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -585,14 +500,12 @@ in the following example: ...@@ -585,14 +500,12 @@ in the following example:
} }
---- ----
NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of `@EnableAutoConfiguration` and `@ComponentScan`.
`@EnableAutoConfiguration` and `@ComponentScan`.
[NOTE] [NOTE]
==== ====
None of these features are mandatory and you may choose to replace this single annotation None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables.
by any of the features that it enables. For instance, you may not want to use component For instance, you may not want to use component scan in your application:
scan in your application:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -615,48 +528,38 @@ scan in your application: ...@@ -615,48 +528,38 @@ scan in your application:
} }
---- ----
In this example, `Application` is just like any other Spring Boot application except that In this example, `Application` is just like any other Spring Boot application except that `@Component`-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see `@Import`).
`@Component`-annotated classes are not detected automatically and the user-defined beans
are imported explicitly (see `@Import`).
==== ====
[[using-boot-running-your-application]] [[using-boot-running-your-application]]
== Running Your Application == Running Your Application
One of the biggest advantages of packaging your application as a jar and using an One of the biggest advantages of packaging your application as a jar and using an embedded HTTP server is that you can run your application as you would any other.
embedded HTTP server is that you can run your application as you would any other. Debugging Spring Boot applications is also easy. You do not need any special IDE plugins or extensions.
Debugging Spring Boot applications is also easy. You do not need any special IDE plugins
or extensions.
NOTE: This section only covers jar based packaging. If you choose to package your NOTE: This section only covers jar based packaging. If you choose to package your application as a war file, you should refer to your server and IDE documentation.
application as a war file, you should refer to your server and IDE documentation.
[[using-boot-running-from-an-ide]] [[using-boot-running-from-an-ide]]
=== Running from an IDE === Running from an IDE
You can run a Spring Boot application from your IDE as a simple Java application. You can run a Spring Boot application from your IDE as a simple Java application.
However, you first need to import your project. Import steps vary depending on your IDE However, you first need to import your project.
and build system. Most IDEs can import Maven projects directly. For example, Eclipse Import steps vary depending on your IDE and build system.
users can select `Import...` -> `Existing Maven Projects` from the `File` menu. Most IDEs can import Maven projects directly.
For example, Eclipse users can select `Import...` -> `Existing Maven Projects` from the `File` menu.
If you cannot directly import your project into your IDE, you may be able to generate IDE If you cannot directly import your project into your IDE, you may be able to generate IDE metadata by using a build plugin. Maven includes plugins for https://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and https://maven.apache.org/plugins/maven-idea-plugin/[IDEA].
metadata by using a build plugin. Maven includes plugins for Gradle offers plugins for {gradle-user-guide}/userguide.html[various IDEs].
https://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and
https://maven.apache.org/plugins/maven-idea-plugin/[IDEA]. Gradle offers plugins for
{gradle-user-guide}/userguide.html[various IDEs].
TIP: If you accidentally run a web application twice, you see a "`Port already in use`" TIP: If you accidentally run a web application twice, you see a "`Port already in use`" error. STS users can use the `Relaunch` button rather than the `Run` button to ensure that any existing instance is closed.
error. STS users can use the `Relaunch` button rather than the `Run` button to ensure
that any existing instance is closed.
[[using-boot-running-as-a-packaged-application]] [[using-boot-running-as-a-packaged-application]]
=== Running as a Packaged Application === Running as a Packaged Application
If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can run your application using `java -jar`, as shown in the following example:
run your application using `java -jar`, as shown in the following example:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
...@@ -664,8 +567,7 @@ run your application using `java -jar`, as shown in the following example: ...@@ -664,8 +567,7 @@ run your application using `java -jar`, as shown in the following example:
---- ----
It is also possible to run a packaged application with remote debugging support enabled. It is also possible to run a packaged application with remote debugging support enabled.
Doing so lets you attach a debugger to your packaged application, as shown in the Doing so lets you attach a debugger to your packaged application, as shown in the following example:
following example:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
...@@ -677,8 +579,8 @@ following example: ...@@ -677,8 +579,8 @@ following example:
[[using-boot-running-with-the-maven-plugin]] [[using-boot-running-with-the-maven-plugin]]
=== Using the Maven Plugin === Using the Maven Plugin
The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile The Spring Boot Maven plugin includes a `run` goal that can be used to quickly compile and run your application.
and run your application. Applications run in an exploded form, as they do in your IDE. Applications run in an exploded form, as they do in your IDE.
The following example shows a typical Maven command to run a Spring Boot application: The following example shows a typical Maven command to run a Spring Boot application:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
...@@ -686,8 +588,7 @@ The following example shows a typical Maven command to run a Spring Boot applica ...@@ -686,8 +588,7 @@ The following example shows a typical Maven command to run a Spring Boot applica
$ mvn spring-boot:run $ mvn spring-boot:run
---- ----
You might also want to use the `MAVEN_OPTS` operating system environment variable, as You might also want to use the `MAVEN_OPTS` operating system environment variable, as shown in the following example:
shown in the following example:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
...@@ -698,17 +599,15 @@ shown in the following example: ...@@ -698,17 +599,15 @@ shown in the following example:
[[using-boot-running-with-the-gradle-plugin]] [[using-boot-running-with-the-gradle-plugin]]
=== Using the Gradle Plugin === Using the Gradle Plugin
The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your The Spring Boot Gradle plugin also includes a `bootRun` task that can be used to run your application in an exploded form.
application in an exploded form. The `bootRun` task is added whenever you apply the The `bootRun` task is added whenever you apply the `org.springframework.boot` and `java` plugins and is shown in the following example:
`org.springframework.boot` and `java` plugins and is shown in the following example:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
$ gradle bootRun $ gradle bootRun
---- ----
You might also want to use the `JAVA_OPTS` operating system environment variable, as You might also want to use the `JAVA_OPTS` operating system environment variable, as shown in the following example:
shown in the following example:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
...@@ -719,25 +618,20 @@ shown in the following example: ...@@ -719,25 +618,20 @@ shown in the following example:
[[using-boot-hot-swapping]] [[using-boot-hot-swapping]]
=== Hot Swapping === Hot Swapping
Since Spring Boot applications are just plain Java applications, JVM hot-swapping should Since Spring Boot applications are just plain Java applications, JVM hot-swapping should work out of the box.
work out of the box. JVM hot swapping is somewhat limited with the bytecode that it can JVM hot swapping is somewhat limited with the bytecode that it can replace.
replace. For a more complete solution, For a more complete solution, https://jrebel.com/software/jrebel/[JRebel] can be used.
https://zeroturnaround.com/software/jrebel/[JRebel] can be used.
The The `spring-boot-devtools` module also includes support for quick application restarts.
`spring-boot-devtools` module also includes support for quick application restarts. See the <<using-boot-devtools>> section later in this chapter and the <<howto.adoc#howto-hotswapping, Hot swapping "`How-to`">> for details.
See the <<using-boot-devtools>> section later in this chapter and the
<<howto.adoc#howto-hotswapping, Hot swapping "`How-to`">> for details.
[[using-boot-devtools]] [[using-boot-devtools]]
== Developer Tools == Developer Tools
Spring Boot includes an additional set of tools that can make the application Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant.
development experience a little more pleasant. The `spring-boot-devtools` module can be The `spring-boot-devtools` module can be included in any project to provide additional development-time features.
included in any project to provide additional development-time features. To include To include devtools support, add the module dependency to your build, as shown in the following listings for Maven and Gradle:
devtools support, add the module dependency to your build, as shown in the following
listings for Maven and Gradle:
.Maven .Maven
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
...@@ -765,121 +659,90 @@ listings for Maven and Gradle: ...@@ -765,121 +659,90 @@ listings for Maven and Gradle:
} }
---- ----
NOTE: Developer tools are automatically disabled when running a fully packaged NOTE: Developer tools are automatically disabled when running a fully packaged application.
application. If your application is launched from `java -jar` or if it is started from a If your application is launched from `java -jar` or if it is started from a special classloader, then it is considered a "`production application`".
special classloader, then it is considered a "`production application`". If that does not If that does not apply to you (i.e. if you run your application from a container), consider excluding devtools or set the `-Dspring.devtools.restart.enabled=false` system property.
apply to you (i.e. if you run your application from a container), consider excluding
devtools or set the `-Dspring.devtools.restart.enabled=false` system property.
TIP: Flagging the dependency as optional in Maven or using a custom`developmentOnly` TIP: Flagging the dependency as optional in Maven or using a custom`developmentOnly` configuration in Gradle (as shown above) is a best practice that prevents devtools from being transitively applied to other modules that use your project.
configuration in Gradle (as shown above) is a best practice that prevents devtools from
being transitively applied to other modules that use your project.
TIP: Repackaged archives do not contain devtools by default. If you want to use a TIP: Repackaged archives do not contain devtools by default. If you want to use a <<using-boot-devtools-remote,certain remote devtools feature>>, you need to disable the `excludeDevtools` build property to include it.
<<using-boot-devtools-remote,certain remote devtools feature>>, you need to disable the The property is supported with both the Maven and Gradle plugins.
`excludeDevtools` build property to include it. The property is supported with both the
Maven and Gradle plugins.
[[using-boot-devtools-property-defaults]] [[using-boot-devtools-property-defaults]]
=== Property Defaults === Property Defaults
Several of the libraries supported by Spring Boot use caches to improve performance. For Several of the libraries supported by Spring Boot use caches to improve performance.
example, <<spring-boot-features#boot-features-spring-mvc-template-engines,template For example, <<spring-boot-features#boot-features-spring-mvc-template-engines,template engines>> cache compiled templates to avoid repeatedly parsing template files.
engines>> cache compiled templates to avoid repeatedly parsing template files. Also, Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
Spring MVC can add HTTP caching headers to responses when serving static resources.
While caching is very beneficial in production, it can be counter-productive during While caching is very beneficial in production, it can be counter-productive during development, preventing you from seeing the changes you just made in your application.
development, preventing you from seeing the changes you just made in your application.
For this reason, spring-boot-devtools disables the caching options by default. For this reason, spring-boot-devtools disables the caching options by default.
Cache options are usually configured by settings in your `application.properties` file. Cache options are usually configured by settings in your `application.properties` file.
For example, Thymeleaf offers the `spring.thymeleaf.cache` property. Rather than needing For example, Thymeleaf offers the `spring.thymeleaf.cache` property.
to set these properties manually, the `spring-boot-devtools` module automatically applies Rather than needing to set these properties manually, the `spring-boot-devtools` module automatically applies sensible development-time configuration.
sensible development-time configuration.
Because you need more information about web requests while developing Spring MVC and Because you need more information about web requests while developing Spring MVC and Spring WebFlux applications, developer tools will enable `DEBUG` logging for the `web` logging group.
Spring WebFlux applications, developer tools will enable `DEBUG` logging for the `web` This will give you information about the incoming request, which handler is processing it, the response outcome, etc.
logging group. This will give you information about the incoming request, which handler is If you wish to log all request details (including potentially sensitive information), you can turn on the `spring.http.log-request-details` configuration property.
processing it, the response outcome, etc. If you wish to log all request details
(including potentially sensitive information), you can turn on the
`spring.http.log-request-details` configuration property.
NOTE: If you don't want property defaults to be applied you can set NOTE: If you don't want property defaults to be applied you can set `spring.devtools.add-properties` to `false` in your `application.properties`.
`spring.devtools.add-properties` to `false` in your `application.properties`.
TIP: For a complete list of the properties that are applied by the devtools, see TIP: For a complete list of the properties that are applied by the devtools, see {sc-spring-boot-devtools}/env/DevToolsPropertyDefaultsPostProcessor.{sc-ext}[DevToolsPropertyDefaultsPostProcessor].
{sc-spring-boot-devtools}/env/DevToolsPropertyDefaultsPostProcessor.{sc-ext}[DevToolsPropertyDefaultsPostProcessor].
[[using-boot-devtools-restart]] [[using-boot-devtools-restart]]
=== Automatic Restart === Automatic Restart
Applications that use `spring-boot-devtools` automatically restart whenever files on the Applications that use `spring-boot-devtools` automatically restart whenever files on the classpath change.
classpath change. This can be a useful feature when working in an IDE, as it gives a very This can be a useful feature when working in an IDE, as it gives a very fast feedback loop for code changes.
fast feedback loop for code changes. By default, any entry on the classpath that points By default, any entry on the classpath that points to a folder is monitored for changes.
to a folder is monitored for changes. Note that certain resources, such as static assets Note that certain resources, such as static assets and view templates, <<using-boot-devtools-restart-exclude, do not need to restart the application>>.
and view templates, <<using-boot-devtools-restart-exclude, do not need to restart the
application>>.
.Triggering a restart .Triggering a restart
**** ****
As DevTools monitors classpath resources, the only way to trigger a restart is to update As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath.
the classpath. The way in which you cause the classpath to be updated depends on the IDE The way in which you cause the classpath to be updated depends on the IDE that you are using.
that you are using. In Eclipse, saving a modified file causes the classpath to be updated In Eclipse, saving a modified file causes the classpath to be updated and triggers a restart.
and triggers a restart. In IntelliJ IDEA, building the project In IntelliJ IDEA, building the project (`Build +->+ Build Project`) has the same effect.
(`Build +->+ Build Project`) has the same effect.
**** ****
[NOTE] NOTE: As long as forking is enabled, you can also start your application by using the supported build plugins (Maven and Gradle), since DevTools needs an isolated application classloader to operate properly.
==== By default, Gradle and Maven do that when they detect DevTools on the classpath.
As long as forking is enabled, you can also start your application by using the supported
build plugins (Maven and Gradle), since DevTools needs an isolated application
classloader to operate properly. By default, Gradle and Maven do that when they detect
DevTools on the classpath.
====
TIP: Automatic restart works very well when used with LiveReload. TIP: Automatic restart works very well when used with LiveReload.
<<using-boot-devtools-livereload,See the LiveReload section>> for details. If you use <<using-boot-devtools-livereload,See the LiveReload section>> for details. If you use JRebel, automatic restarts are disabled in favor of dynamic class reloading.
JRebel, automatic restarts are disabled in favor of dynamic class reloading. Other Other devtools features (such as LiveReload and property overrides) can still be used.
devtools features (such as LiveReload and property overrides) can still be used.
NOTE: DevTools relies on the application context's shutdown hook to close it during a NOTE: DevTools relies on the application context's shutdown hook to close it during a restart.
restart. It does not work correctly if you have disabled the shutdown hook It does not work correctly if you have disabled the shutdown hook (`SpringApplication.setRegisterShutdownHook(false)`).
(`SpringApplication.setRegisterShutdownHook(false)`).
NOTE: When deciding if an entry on the classpath should trigger a restart when it NOTE: When deciding if an entry on the classpath should trigger a restart when it changes, DevTools automatically ignores projects named `spring-boot`, `spring-boot-devtools`, `spring-boot-autoconfigure`, `spring-boot-actuator`, and `spring-boot-starter`.
changes, DevTools automatically ignores projects named `spring-boot`,
`spring-boot-devtools`, `spring-boot-autoconfigure`, `spring-boot-actuator`, and
`spring-boot-starter`.
NOTE: DevTools needs to customize the `ResourceLoader` used by the `ApplicationContext`. NOTE: DevTools needs to customize the `ResourceLoader` used by the `ApplicationContext`.
If your application provides one already, it is going to be wrapped. Direct override of If your application provides one already, it is going to be wrapped.
the `getResource` method on the `ApplicationContext` is not supported. Direct override of the `getResource` method on the `ApplicationContext` is not supported.
[[using-spring-boot-restart-vs-reload]] [[using-spring-boot-restart-vs-reload]]
.Restart vs Reload .Restart vs Reload
**** ****
The restart technology provided by Spring Boot works by using two classloaders. Classes The restart technology provided by Spring Boot works by using two classloaders.
that do not change (for example, those from third-party jars) are loaded into a _base_ Classes that do not change (for example, those from third-party jars) are loaded into a _base_ classloader.
classloader. Classes that you are actively developing are loaded into a _restart_ Classes that you are actively developing are loaded into a _restart_ classloader.
classloader. When the application is restarted, the _restart_ classloader is thrown away When the application is restarted, the _restart_ classloader is thrown away and a new one is created.
and a new one is created. This approach means that application restarts are typically This approach means that application restarts are typically much faster than "`cold starts`", since the _base_ classloader is already available and populated.
much faster than "`cold starts`", since the _base_ classloader is already available and
populated. If you find that restarts are not quick enough for your applications or you encounter classloading issues, you could consider reloading technologies such as https://jrebel.com/software/jrebel/[JRebel] from ZeroTurnaround.
These work by rewriting classes as they are loaded to make them more amenable to reloading.
If you find that restarts are not quick enough for your applications or you encounter
classloading issues, you could consider reloading technologies such as
https://zeroturnaround.com/software/jrebel/[JRebel] from ZeroTurnaround. These work by
rewriting classes as they are loaded to make them more amenable to reloading.
**** ****
[[using-boot-devtools-restart-logging-condition-delta]] [[using-boot-devtools-restart-logging-condition-delta]]
==== Logging changes in condition evaluation ==== Logging changes in condition evaluation
By default, each time your application restarts, a report showing the condition evaluation By default, each time your application restarts, a report showing the condition evaluation delta is logged.
delta is logged. The report shows the changes to your application's auto-configuration as The report shows the changes to your application's auto-configuration as you make changes such as adding or removing beans and setting configuration properties.
you make changes such as adding or removing beans and setting configuration properties.
To disable the logging of the report, set the following property: To disable the logging of the report, set the following property:
...@@ -891,46 +754,35 @@ To disable the logging of the report, set the following property: ...@@ -891,46 +754,35 @@ To disable the logging of the report, set the following property:
[[using-boot-devtools-restart-exclude]] [[using-boot-devtools-restart-exclude]]
==== Excluding Resources ==== Excluding Resources
Certain resources do not necessarily need to trigger a restart when they are changed. For Certain resources do not necessarily need to trigger a restart when they are changed.
example, Thymeleaf templates can be edited in-place. By default, changing resources For example, Thymeleaf templates can be edited in-place.
in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or By default, changing resources in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public`, or `/templates` does not trigger a restart but does trigger a <<using-boot-devtools-livereload, live reload>>.
`/templates` does not trigger a restart but does trigger a If you want to customize these exclusions, you can use the `spring.devtools.restart.exclude` property.
<<using-boot-devtools-livereload, live reload>>. If you want to customize these For example, to exclude only `/static` and `/public` you would set the following property:
exclusions, you can use the `spring.devtools.restart.exclude` property. For example, to
exclude only `/static` and `/public` you would set the following property:
[indent=0] [indent=0]
---- ----
spring.devtools.restart.exclude=static/**,public/** spring.devtools.restart.exclude=static/**,public/**
---- ----
TIP: If you want to keep those defaults and _add_ additional exclusions, use the TIP: If you want to keep those defaults and _add_ additional exclusions, use the `spring.devtools.restart.additional-exclude` property instead.
`spring.devtools.restart.additional-exclude` property instead.
[[using-boot-devtools-restart-additional-paths]] [[using-boot-devtools-restart-additional-paths]]
==== Watching Additional Paths ==== Watching Additional Paths
You may want your application to be restarted or reloaded when you make changes to files You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath.
that are not on the classpath. To do so, use the To do so, use the `spring.devtools.restart.additional-paths` property to configure additional paths to watch for changes.
`spring.devtools.restart.additional-paths` property to configure additional paths to You can use the `spring.devtools.restart.exclude` property <<using-boot-devtools-restart-exclude, described earlier>> to control whether changes beneath the additional paths trigger a full restart or a <<using-boot-devtools-livereload, live reload>>.
watch for changes. You can use the `spring.devtools.restart.exclude` property
<<using-boot-devtools-restart-exclude, described earlier>> to control whether changes
beneath the additional paths trigger a full restart or a
<<using-boot-devtools-livereload, live reload>>.
[[using-boot-devtools-restart-disable]] [[using-boot-devtools-restart-disable]]
==== Disabling Restart ==== Disabling Restart
If you do not want to use the restart feature, you can disable it by using the If you do not want to use the restart feature, you can disable it by using the `spring.devtools.restart.enabled` property.
`spring.devtools.restart.enabled` property. In most cases, you can set this property in In most cases, you can set this property in your `application.properties` (doing so still initializes the restart classloader, but it does not watch for file changes).
your `application.properties` (doing so still initializes the restart classloader, but it
does not watch for file changes).
If you need to _completely_ disable restart support (for example, because it does not work If you need to _completely_ disable restart support (for example, because it does not work with a specific library), you need to set the `spring.devtools.restart.enabled` `System` property to `false` before calling `SpringApplication.run(...)`, as shown in the following example:
with a specific library), you need to set the `spring.devtools.restart.enabled` `System`
property to `false` before calling `SpringApplication.run(...)`, as shown in the
following example:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -944,38 +796,30 @@ following example: ...@@ -944,38 +796,30 @@ following example:
[[using-boot-devtools-restart-triggerfile]] [[using-boot-devtools-restart-triggerfile]]
==== Using a Trigger File ==== Using a Trigger File
If you work with an IDE that continuously compiles changed files, you might prefer to If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times.
trigger restarts only at specific times. To do so, you can use a "`trigger file`", which To do so, you can use a "`trigger file`", which is a special file that must be modified when you want to actually trigger a restart check.
is a special file that must be modified when you want to actually trigger a restart Changing the file only triggers the check and the restart only occurs if Devtools has detected it has to do something.
check. Changing the file only triggers the check and the restart only occurs if The trigger file can be updated manually or with an IDE plugin.
Devtools has detected it has to do something. The trigger file can be updated manually or
with an IDE plugin.
To use a trigger file, set the `spring.devtools.restart.trigger-file` property to the To use a trigger file, set the `spring.devtools.restart.trigger-file` property to the path of your trigger file.
path of your trigger file.
TIP: You might want to set `spring.devtools.restart.trigger-file` as a TIP: You might want to set `spring.devtools.restart.trigger-file` as a <<using-boot-devtools-globalsettings,global setting>>, so that all your projects behave in the same way.
<<using-boot-devtools-globalsettings,global setting>>, so that all your projects behave
in the same way.
[[using-boot-devtools-customizing-classload]] [[using-boot-devtools-customizing-classload]]
==== Customizing the Restart Classloader ==== Customizing the Restart Classloader
As described earlier in the <<using-spring-boot-restart-vs-reload>> section, restart As described earlier in the <<using-spring-boot-restart-vs-reload>> section, restart functionality is implemented by using two classloaders.
functionality is implemented by using two classloaders. For most applications, this For most applications, this approach works well.
approach works well. However, it can sometimes cause classloading issues. However, it can sometimes cause classloading issues.
By default, any open project in your IDE is loaded with the "`restart`" classloader, and By default, any open project in your IDE is loaded with the "`restart`" classloader, and any regular `.jar` file is loaded with the "`base`" classloader.
any regular `.jar` file is loaded with the "`base`" classloader. If you work on a If you work on a multi-module project, and not every module is imported into your IDE, you may need to customize things.
multi-module project, and not every module is imported into your IDE, you may need to To do so, you can create a `META-INF/spring-devtools.properties` file.
customize things. To do so, you can create a `META-INF/spring-devtools.properties` file.
The `spring-devtools.properties` file can contain properties prefixed with The `spring-devtools.properties` file can contain properties prefixed with `restart.exclude` and `restart.include`.
`restart.exclude` and `restart.include`. The `include` elements are items that should be The `include` elements are items that should be pulled up into the "`restart`" classloader, and the `exclude` elements are items that should be pushed down into the "`base`" classloader.
pulled up into the "`restart`" classloader, and the `exclude` elements are items that The value of the property is a regex pattern that is applied to the classpath, as shown in the following example:
should be pushed down into the "`base`" classloader. The value of the property is a regex
pattern that is applied to the classpath, as shown in the following example:
[source,properties,indent=0] [source,properties,indent=0]
---- ----
...@@ -983,51 +827,40 @@ pattern that is applied to the classpath, as shown in the following example: ...@@ -983,51 +827,40 @@ pattern that is applied to the classpath, as shown in the following example:
restart.include.projectcommon=/mycorp-myproj-[\\w\\d-\.]+\.jar restart.include.projectcommon=/mycorp-myproj-[\\w\\d-\.]+\.jar
---- ----
NOTE: All property keys must be unique. As long as a property starts with NOTE: All property keys must be unique. As long as a property starts with `restart.include.` or `restart.exclude.` it is considered.
`restart.include.` or `restart.exclude.` it is considered.
TIP: All `META-INF/spring-devtools.properties` from the classpath are loaded. You can TIP: All `META-INF/spring-devtools.properties` from the classpath are loaded.
package files inside your project, or in the libraries that the project consumes. You can package files inside your project, or in the libraries that the project consumes.
[[using-boot-devtools-known-restart-limitations]] [[using-boot-devtools-known-restart-limitations]]
==== Known Limitations ==== Known Limitations
Restart functionality does not work well with objects that are deserialized by using a Restart functionality does not work well with objects that are deserialized by using a standard `ObjectInputStream`.
standard `ObjectInputStream`. If you need to deserialize data, you may need to use If you need to deserialize data, you may need to use Spring's `ConfigurableObjectInputStream` in combination with `Thread.currentThread().getContextClassLoader()`.
Spring's `ConfigurableObjectInputStream` in combination with
`Thread.currentThread().getContextClassLoader()`.
Unfortunately, several third-party libraries deserialize without considering the context Unfortunately, several third-party libraries deserialize without considering the context classloader.
classloader. If you find such a problem, you need to request a fix with the original If you find such a problem, you need to request a fix with the original authors.
authors.
[[using-boot-devtools-livereload]] [[using-boot-devtools-livereload]]
=== LiveReload === LiveReload
The `spring-boot-devtools` module includes an embedded LiveReload server that can be used The `spring-boot-devtools` module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed.
to trigger a browser refresh when a resource is changed. LiveReload browser extensions LiveReload browser extensions are freely available for Chrome, Firefox and Safari from http://livereload.com/extensions/[livereload.com].
are freely available for Chrome, Firefox and Safari from
http://livereload.com/extensions/[livereload.com].
If you do not want to start the LiveReload server when your application runs, you can set If you do not want to start the LiveReload server when your application runs, you can set the `spring.devtools.livereload.enabled` property to `false`.
the `spring.devtools.livereload.enabled` property to `false`.
NOTE: You can only run one LiveReload server at a time. Before starting your application, NOTE: You can only run one LiveReload server at a time. Before starting your application, ensure that no other LiveReload servers are running.
ensure that no other LiveReload servers are running. If you start multiple applications If you start multiple applications from your IDE, only the first has LiveReload support.
from your IDE, only the first has LiveReload support.
[[using-boot-devtools-globalsettings]] [[using-boot-devtools-globalsettings]]
=== Global Settings === Global Settings
You can configure global devtools settings by adding a file named You can configure global devtools settings by adding a file named `.spring-boot-devtools.properties` to your `$HOME` folder (note that the filename starts with "`.`").
`.spring-boot-devtools.properties` to your `$HOME` folder (note that the filename starts Any properties added to this file apply to _all_ Spring Boot applications on your machine that use devtools.
with "`.`"). Any properties added to this file apply to _all_ Spring Boot applications on For example, to configure restart to always use a <<using-boot-devtools-restart-triggerfile, trigger file>>, you would add the following property:
your machine that use devtools. For example, to configure restart to always use a
<<using-boot-devtools-restart-triggerfile, trigger file>>, you would add the following
property:
.~/.spring-boot-devtools.properties .~/.spring-boot-devtools.properties
[source,properties,indent=0] [source,properties,indent=0]
...@@ -1035,18 +868,16 @@ property: ...@@ -1035,18 +868,16 @@ property:
spring.devtools.reload.trigger-file=.reloadtrigger spring.devtools.reload.trigger-file=.reloadtrigger
---- ----
NOTE: Profiles activated in `.spring-boot-devtools.properties` will not affect the NOTE: Profiles activated in `.spring-boot-devtools.properties` will not affect the loading of <<spring-boot-features.adoc#boot-features-external-config-profile-specific-properties, profile-specific configuration files>>.
loading of <<spring-boot-features.adoc#boot-features-external-config-profile-specific-properties,
profile-specific configuration files>>.
[[using-boot-devtools-remote]] [[using-boot-devtools-remote]]
=== Remote Applications === Remote Applications
The Spring Boot developer tools are not limited to local development. You can also The Spring Boot developer tools are not limited to local development.
use several features when running applications remotely. Remote support is opt-in. To You can also use several features when running applications remotely.
enable it, you need to make sure that `devtools` is included in the repackaged archive, Remote support is opt-in.
as shown in the following listing: To enable it, you need to make sure that `devtools` is included in the repackaged archive, as shown in the following listing:
[source,xml,indent=0,subs="verbatim,quotes,attributes"] [source,xml,indent=0,subs="verbatim,quotes,attributes"]
---- ----
...@@ -1063,39 +894,34 @@ as shown in the following listing: ...@@ -1063,39 +894,34 @@ as shown in the following listing:
</build> </build>
---- ----
Then you need to set a `spring.devtools.remote.secret` property, as shown in the Then you need to set a `spring.devtools.remote.secret` property, as shown in the following example:
following example:
[source,properties,indent=0] [source,properties,indent=0]
---- ----
spring.devtools.remote.secret=mysecret spring.devtools.remote.secret=mysecret
---- ----
WARNING: Enabling `spring-boot-devtools` on a remote application is a security risk. You WARNING: Enabling `spring-boot-devtools` on a remote application is a security risk.
should never enable support on a production deployment. You should never enable support on a production deployment.
Remote devtools support is provided in two parts: a server-side endpoint that accepts Remote devtools support is provided in two parts: a server-side endpoint that accepts connections and a client application that you run in your IDE.
connections and a client application that you run in your IDE. The server component is The server component is automatically enabled when the `spring.devtools.remote.secret` property is set.
automatically enabled when the `spring.devtools.remote.secret` property is set. The The client component must be launched manually.
client component must be launched manually.
==== Running the Remote Client Application ==== Running the Remote Client Application
The remote client application is designed to be run from within your IDE. You need to run The remote client application is designed to be run from within your IDE.
`org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as You need to run `org.springframework.boot.devtools.RemoteSpringApplication` with the same classpath as the remote project that you connect to.
the remote project that you connect to. The application's single required argument is the The application's single required argument is the remote URL to which it connects.
remote URL to which it connects.
For example, if you are using Eclipse or STS and you have a project named `my-app` that For example, if you are using Eclipse or STS and you have a project named `my-app` that you have deployed to Cloud Foundry, you would do the following:
you have deployed to Cloud Foundry, you would do the following:
* Select `Run Configurations...` from the `Run` menu. * Select `Run Configurations...` from the `Run` menu.
* Create a new `Java Application` "`launch configuration`". * Create a new `Java Application` "`launch configuration`".
* Browse for the `my-app` project. * Browse for the `my-app` project.
* Use `org.springframework.boot.devtools.RemoteSpringApplication` as the main class. * Use `org.springframework.boot.devtools.RemoteSpringApplication` as the main class.
* Add `+++https://myapp.cfapps.io+++` to the `Program arguments` (or whatever your remote * Add `+++https://myapp.cfapps.io+++` to the `Program arguments` (or whatever your remote URL is).
URL is).
A running remote client might resemble the following listing: A running remote client might resemble the following listing:
...@@ -1116,47 +942,39 @@ A running remote client might resemble the following listing: ...@@ -1116,47 +942,39 @@ A running remote client might resemble the following listing:
2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105) 2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105)
---- ----
NOTE: Because the remote client is using the same classpath as the real application it NOTE: Because the remote client is using the same classpath as the real application it can directly read application properties.
can directly read application properties. This is how the `spring.devtools.remote.secret` This is how the `spring.devtools.remote.secret` property is read and passed to the server for authentication.
property is read and passed to the server for authentication.
TIP: It is always advisable to use `https://` as the connection protocol, so that traffic TIP: It is always advisable to use `https://` as the connection protocol, so that traffic is encrypted and passwords cannot be intercepted.
is encrypted and passwords cannot be intercepted.
TIP: If you need to use a proxy to access the remote application, configure the TIP: If you need to use a proxy to access the remote application, configure the `spring.devtools.remote.proxy.host` and `spring.devtools.remote.proxy.port` properties.
`spring.devtools.remote.proxy.host` and `spring.devtools.remote.proxy.port` properties.
[[using-boot-devtools-remote-update]] [[using-boot-devtools-remote-update]]
==== Remote Update ==== Remote Update
The remote client monitors your application classpath for changes in the same way as the The remote client monitors your application classpath for changes in the same way as the <<using-boot-devtools-restart,local restart>>.
<<using-boot-devtools-restart,local restart>>. Any updated resource is pushed to the Any updated resource is pushed to the remote application and (_if required_) triggers a restart.
remote application and (_if required_) triggers a restart. This can be helpful if you This can be helpful if you iterate on a feature that uses a cloud service that you do not have locally.
iterate on a feature that uses a cloud service that you do not have locally. Generally, Generally, remote updates and restarts are much quicker than a full rebuild and deploy cycle.
remote updates and restarts are much quicker than a full rebuild and deploy cycle.
NOTE: Files are only monitored when the remote client is running.
If you change a file before starting the remote client, it is not pushed to the remote server.
NOTE: Files are only monitored when the remote client is running. If you change a file
before starting the remote client, it is not pushed to the remote server.
[[configuring-file-system-watcher]] [[configuring-file-system-watcher]]
==== Configuring File System Watcher ==== Configuring File System Watcher
{sc-spring-boot-devtools}/filewatch/FileSystemWatcher.{sc-ext}[FileSystemWatcher] works {sc-spring-boot-devtools}/filewatch/FileSystemWatcher.{sc-ext}[FileSystemWatcher] works by polling the class changes with a certain time interval, and then waiting for a predefined quiet period to make sure there are no more changes.
by polling the class changes with a certain time interval, and then waiting for a The changes are then uploaded to the remote application.
predefined quiet period to make sure there are no more changes. The changes are then On a slower development environment, it may happen that the quiet period is not enough, and the changes in the classes may be split into batches.
uploaded to the remote application. On a slower development environment, it may happen
that the quiet period is not enough, and the changes in the classes may be split into batches.
The server is restarted after the first batch of class changes is uploaded. The server is restarted after the first batch of class changes is uploaded.
The next batch can’t be sent to the application, since the server is restarting. The next batch can’t be sent to the application, since the server is restarting.
This is typically manifested by a warning in the `RemoteSpringApplication` logs about This is typically manifested by a warning in the `RemoteSpringApplication` logs about failing to upload some of the classes, and a consequent retry.
failing to upload some of the classes, and a consequent retry. But it may also lead to But it may also lead to application code inconsistency and failure to restart after the first batch of changes is uploaded.
application code inconsistency and failure to restart after the first batch of changes is
uploaded.
If you observe such problems constantly, try increasing the If you observe such problems constantly, try increasing the `spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period` parameters to the values that fit your development environment:
`spring.devtools.restart.poll-interval` and `spring.devtools.restart.quiet-period`
parameters to the values that fit your development environment:
[source,properties,indent=0] [source,properties,indent=0]
---- ----
...@@ -1164,22 +982,21 @@ parameters to the values that fit your development environment: ...@@ -1164,22 +982,21 @@ parameters to the values that fit your development environment:
spring.devtools.restart.quiet-period=1s spring.devtools.restart.quiet-period=1s
---- ----
The monitored classpath folders are now polled every 2 seconds for changes, and a 1 second The monitored classpath folders are now polled every 2 seconds for changes, and a 1 second quiet period is maintained to make sure there are no additional class changes.
quiet period is maintained to make sure there are no additional class changes.
[[security-configuration-for-devtools-remote]] [[security-configuration-for-devtools-remote]]
==== Security Configuration for Devtools Remote ==== Security Configuration for Devtools Remote
If you have Spring Security on the classpath, you may observe HTTP error 401 or 403 in If you have Spring Security on the classpath, you may observe HTTP error 401 or 403 in the logs of the `RemoteSpringApplication`:
the logs of the `RemoteSpringApplication`:
[indent=0,subs="attributes"] [indent=0,subs="attributes"]
---- ----
Exception in thread "File Watcher" java.lang.IllegalStateException: Unexpected 401 UNAUTHORIZED response uploading class files Exception in thread "File Watcher" java.lang.IllegalStateException: Unexpected 401 UNAUTHORIZED response uploading class files
---- ----
The URL for class uploading should be exempted both from the web security and from the The URL for class uploading should be exempted both from the web security and from the csrf filter.
csrf filter. The following example shows how anonymous access to the remote devtools endpoint The following example shows how anonymous access to the remote devtools endpoint can be configured:
can be configured:
[source,java,indent=0] [source,java,indent=0]
---- ----
...@@ -1195,27 +1012,23 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { ...@@ -1195,27 +1012,23 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} }
---- ----
NOTE: The above configuration will only affect the remote devtools endpoint. Spring Boot's default NOTE: The above configuration will only affect the remote devtools endpoint.
security auto-configuration will still apply to the rest of the application. If the rest Spring Boot's default security auto-configuration will still apply to the rest of the application.
of the application requires custom security, it needs to be configured separately. If the rest of the application requires custom security, it needs to be configured separately.
[[using-boot-packaging-for-production]] [[using-boot-packaging-for-production]]
== Packaging Your Application for Production == Packaging Your Application for Production
Executable jars can be used for production deployment. As they are self-contained, they Executable jars can be used for production deployment.
are also ideally suited for cloud-based deployment. As they are self-contained, they are also ideally suited for cloud-based deployment.
For additional "`production ready`" features, such as health, auditing, and metric REST For additional "`production ready`" features, such as health, auditing, and metric REST or JMX end-points, consider adding `spring-boot-actuator`.
or JMX end-points, consider adding `spring-boot-actuator`. See See _<<production-ready-features.adoc#production-ready>>_ for details.
_<<production-ready-features.adoc#production-ready>>_ for details.
[[using-boot-whats-next]] [[using-boot-whats-next]]
== What to Read Next == What to Read Next
You should now understand how you can use Spring Boot and some best practices that you You should now understand how you can use Spring Boot and some best practices that you should follow.
should follow. You can now go on to learn about specific You can now go on to learn about specific _<<spring-boot-features#boot-features, Spring Boot features>>_ in depth, or you could skip ahead and read about the "`<<production-ready-features#production-ready, production ready>>`" aspects of Spring Boot.
_<<spring-boot-features#boot-features, Spring Boot features>>_ in depth, or you could
skip ahead and read about the "`<<production-ready-features#production-ready, production
ready>>`" aspects of Spring Boot.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment