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