[[using-boot]]
= Using Spring Boot

[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, will make your development process just a
little easier.

If you're just 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 one
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 will not be particularly well
supported.



[[using-boot-dependency-management]]
=== Dependency management
Each release of Spring Boot provides a curated list of dependencies it supports. In
practice, you do not need to provide a version for any of these dependencies in your
build configuration as Spring Boot is managing that for you. When you upgrade Spring
Boot itself, these dependencies will be upgraded as well in a consistent way.

NOTE: You can still specify a version and override Spring Boot's recommendations if you
feel that's necessary.

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`)>>
and additional dedicated support for <<using-boot-maven-parent-pom,Maven>> and
<<build-tool-plugins-gradle-dependency-management,Gradle>> are available as well.

WARNING: Each release of Spring Boot is associated with a base version of the Spring
Framework so we **highly** recommend you to not specify its version on your own.



[[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:

* Java 1.6 as the default compiler level.
* UTF-8 source encoding.
* A <<using-boot-dependency-management,Dependency Management section>>, allowing you to
  omit `<version>` tags for common dependencies, inherited from the
  `spring-boot-dependencies` POM.
* Sensible https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html[resource filtering].
* Sensible plugin configuration (http://www.mojohaus.org/exec-maven-plugin/[exec plugin],
  http://maven.apache.org/surefire/maven-surefire-plugin/[surefire],
  https://github.com/ktoso/maven-git-commit-id-plugin[Git commit ID],
  http://maven.apache.org/plugins/maven-shade-plugin/[shade]).
* Sensible resource filtering for `application.properties` and `application.yml` including
  profile-specific files (e.g. `application-foo.properties` and `application-foo.yml`)

On the last point: since the default config files accept
Spring style placeholders (`${...}`) the Maven filtering is changed to
use `@..@` placeholders (you can override that with a Maven property
`resource.delimiter`).



[[using-boot-maven-parent-pom]]
==== Inheriting the starter parent
To configure your project to inherit from the `spring-boot-starter-parent` simply set
the `parent`:

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<!-- Inherit defaults from Spring Boot -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>{spring-boot-version}</version>
	</parent>
----

NOTE: You should only need to specify 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'd
add the following to your `pom.xml`.

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<properties>
		<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
	</properties>
----

TIP: Check the {github-code}/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 just prefer to explicitly
declare all your Maven configuration.

If you don't 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:

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<dependencyManagement>
 		<dependencies>
			<dependency>
				<!-- Import dependency management from Spring Boot -->
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>{spring-boot-version}</version>
				<type>pom</type>
		        <scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
----

That setup does not allow you to override individual dependencies using a property as
explained above. To achieve the same result, you'd 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'd add the
following to your `pom.xml`.

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<dependencyManagement>
		<dependencies>
			<!-- Override Spring Data release train provided by Spring Boot -->
			<dependency>
				<groupId>org.springframework.data</groupId>
				<artifactId>spring-data-releasetrain</artifactId>
				<version>Fowler-SR2</version>
				<scope>import</scope>
				<type>pom</type>
			</dependency>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>{spring-boot-version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
----

NOTE: In the example above, we specify a _BOM_ but any dependency type can be overridden
that way.



[[using-boot-maven-java-version]]
==== Changing the Java version
The `spring-boot-starter-parent` chooses fairly conservative Java compatibility. If you
want to follow our recommendation and use a later Java version you can add a
`java.version` property:

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<properties>
		<java.version>1.8</java.version>
	</properties>
----



[[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:

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
----

NOTE: If you use the Spring Boot starter parent pom, you only need to add the plugin,
there is no need for to configure it unless you want to change the settings defined in
the parent.



[[using-boot-gradle]]
=== Gradle
Gradle users can directly import '`starters`' in their `dependencies` section. Unlike
Maven, there is no "`super parent`" to import to share some configuration.

[source,groovy,indent=0,subs="attributes"]
----
	repositories {
ifeval::["{spring-boot-repo}" != "release"]
		maven { url "http://repo.spring.io/snapshot" }
		maven { url "http://repo.spring.io/milestone" }
endif::[]
ifeval::["{spring-boot-repo}" == "release"]
		jcenter()
endif::[]
	}

	dependencies {
		compile("org.springframework.boot:spring-boot-starter-web:{spring-boot-version}")
	}
----

The <<build-tool-plugins.adoc#build-tool-plugins-gradle-plugin,
`spring-boot-gradle-plugin`>> is also available and provides tasks to create executable
jars and run projects from source. It also provides
<<build-tool-plugins-gradle-dependency-management, dependency management>> that, among
other capabilities, allows you to omit the version number for any dependencies that are
managed by Spring Boot:

[source,groovy,indent=0,subs="attributes"]
----
ifeval::["{spring-boot-repo}" == "release"]
	plugins {
		id 'org.springframework.boot' version '{spring-boot-version}'
		id 'java'
	}
endif::[]
ifeval::["{spring-boot-repo}" != "release"]
	buildscript {
		repositories {
			jcenter()
			maven { url 'http://repo.spring.io/snapshot' }
			maven { url 'http://repo.spring.io/milestone' }
		}
		dependencies {
			classpath 'org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-version}'
		}
	}

	apply plugin: 'java'
	apply plugin: 'org.springframework.boot'
endif::[]

	repositories {
		jcenter()
ifeval::["{spring-boot-repo}" != "release"]
		maven { url 'http://repo.spring.io/snapshot' }
		maven { url 'http://repo.spring.io/milestone' }
endif::[]
	}

	dependencies {
		compile("org.springframework.boot:spring-boot-starter-web")
		testCompile("org.springframework.boot:spring-boot-starter-test")
	}
----



[[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.

To declare dependencies a typical `ivy.xml` file will look something like this:

[source,xml,indent=0]
----
	<ivy-module version="2.0">
		<info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
		<configurations>
			<conf name="compile" description="everything needed to compile this module" />
			<conf name="runtime" extends="compile" description="everything needed to run this module" />
		</configurations>
		<dependencies>
			<dependency org="org.springframework.boot" name="spring-boot-starter"
				rev="${spring-boot.version}" conf="compile" />
		</dependencies>
	</ivy-module>
----

A typical `build.xml` will look like this:

[source,xml,indent=0]
----
	<project
		xmlns:ivy="antlib:org.apache.ivy.ant"
		xmlns:spring-boot="antlib:org.springframework.boot.ant"
		name="myapp" default="build">

		<property name="spring-boot.version" value="1.3.0.BUILD-SNAPSHOT" />

		<target name="resolve" description="--> retrieve dependencies with ivy">
			<ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
		</target>

		<target name="classpaths" depends="resolve">
			<path id="compile.classpath">
				<fileset dir="lib/compile" includes="*.jar" />
			</path>
		</target>

		<target name="init" depends="classpaths">
			<mkdir dir="build/classes" />
		</target>

		<target name="compile" depends="init" description="compile">
			<javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
		</target>

		<target name="build" depends="compile">
			<spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
				<spring-boot:lib>
					<fileset dir="lib/runtime" />
				</spring-boot:lib>
			</spring-boot:exejar>
		</target>
	</project>
----

TIP: See the _<<howto.adoc#howto-build-an-executable-archive-with-ant>>_ "`How-to`" if
you don't want to use the `spring-boot-antlib` module.



[[using-boot-starter-poms]]
[[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 technology 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, just include the `spring-boot-starter-data-jpa` dependency in your project, and
you are good to go.

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 allow you to
search dependencies by name. For example, with the appropriate Eclipse or STS plugin
installed, you can simply hit `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. A third-party starter for `acme` will be typically named
`acme-spring-boot-starter`.
****

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:

.Spring Boot production starters
include::../../../target/generated-resources/production-starters.adoc[]

Finally, Spring Boot also includes some 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-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.



[[using-boot-using-the-default-package]]
=== Using the "`default`" package
When a class doesn't 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 `@ComponentScan`, `@EntityScan` or `@SpringBootApplication` annotations, since every
class from every jar, will be read.

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 `@EnableAutoConfiguration` 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
`@EnableAutoConfiguration` annotated class will be used to search for `@Entity` items.

Using a root package also allows the `@ComponentScan` annotation to be used without
needing to specify a `basePackage` attribute. You can also use the
`@SpringBootApplication` annotation if your main class is in the root package.

Here is a typical layout:

[indent=0]
----
	com
	 +- example
	     +- myproject
	         +- Application.java
	         |
	         +- domain
	         |   +- Customer.java
	         |   +- CustomerRepository.java
	         |
	         +- service
	         |   +- CustomerService.java
	         |
	         +- web
	             +- CustomerController.java
----

The `Application.java` file would declare the `main` method, along with the basic
`@Configuration`.

[source,java,indent=0]
----
	package com.example.myproject;

	import org.springframework.boot.SpringApplication;
	import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
	import org.springframework.context.annotation.ComponentScan;
	import org.springframework.context.annotation.Configuration;

	@Configuration
	@EnableAutoConfiguration
	@ComponentScan
	public class Application {

		public static void main(String[] args) {
			SpringApplication.run(Application.class, args);
		}

	}
----



[[using-boot-configuration-classes]]
== Configuration classes
Spring Boot favors Java-based configuration. Although it is possible to call
`SpringApplication.run()` with an XML source, we generally recommend that your primary
source is a `@Configuration` class. Usually the class that defines the `main` method
is also a good candidate as the primary `@Configuration`.

TIP: Many Spring configuration examples have been published on the Internet that use XML
configuration. Always try to use the equivalent Java-based configuration if possible.
Searching for `+Enable*+` annotations can be a good starting point.



[[using-boot-importing-configuration]]
=== Importing additional configuration classes
You don't need to 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 additional `@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 we will auto-configure 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.

TIP: You should only ever add one `@EnableAutoConfiguration` annotation. We generally
recommend that you add it to your primary `@Configuration` class.



[[using-boot-replacing-auto-configuration]]
=== Gradually replacing auto-configuration
Auto-configuration is noninvasive,  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 will back away.

If you need to find out what auto-configuration is currently being applied, and why,
start your application with the `--debug` switch. This will enable debug logs for a
selection of core loggers and log an auto-configuration report to the console.



[[using-boot-disabling-specific-auto-configuration]]
=== Disabling specific auto-configuration
If you find that specific auto-configure classes are being applied that you don't want,
you can use the exclude attribute of `@EnableAutoConfiguration` to disable them.

[source,java,indent=0]
----
	import org.springframework.boot.autoconfigure.*;
	import org.springframework.boot.autoconfigure.jdbc.*;
	import org.springframework.context.annotation.*;

	@Configuration
	@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
	public class MyConfiguration {
	}
----

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 via the
`spring.autoconfigure.exclude` property.

TIP: You can define exclusions both at the annotation level and using the property.

[[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, in combination with `@Autowired` 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.) will be
automatically registered as Spring Beans.

Here is an example `@Service` Bean that uses constructor injection to obtain a
required `RiskAssessor` bean.

[source,java,indent=0]
----
	package com.example.service;

	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.stereotype.Service;

	@Service
	public class DatabaseAccountService implements AccountService {

		private final RiskAssessor riskAssessor;

		@Autowired
		public DatabaseAccountService(RiskAssessor riskAssessor) {
			this.riskAssessor = riskAssessor;
		}

		// ...

	}
----

And if a bean has one constructor, you can omit the `@Autowired`.

[source,java,indent=0]
----
	@Service
	public class DatabaseAccountService implements AccountService {

		private final RiskAssessor riskAssessor;

		public DatabaseAccountService(RiskAssessor riskAssessor) {
			this.riskAssessor = riskAssessor;
		}

		// ...

	}
----

TIP: Notice how using constructor injection allows the `riskAssessor` field to be marked
as `final`, indicating that it cannot be subsequently changed.



[[using-boot-using-springbootapplication-annotation]]
== Using the @SpringBootApplication annotation
Many Spring Boot developers always have their main class annotated with `@Configuration`,
`@EnableAutoConfiguration` and `@ComponentScan`. Since these annotations are so frequently
used together (especially if you follow the <<using-boot-structuring-your-code, best practices>>
above), Spring Boot provides a convenient `@SpringBootApplication` alternative.

The `@SpringBootApplication` annotation is equivalent to using `@Configuration`,
`@EnableAutoConfiguration` and `@ComponentScan` with their default attributes:


[source,java,indent=0]
----
	package com.example.myproject;

	import org.springframework.boot.SpringApplication;
	import org.springframework.boot.autoconfigure.SpringBootApplication;

	@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
	public class Application {

		public static void main(String[] args) {
			SpringApplication.run(Application.class, args);
		}

	}
----

NOTE: `@SpringBootApplication` also provides aliases to customize the attributes of
`@EnableAutoConfiguration` and `@ComponentScan`.



[[using-boot-running-your-application]]
== Running your application
One of the biggest advantages of packaging your application as 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 don't 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.



[[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,
first you will need to import your project. Import steps will 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 can't directly import your project into your IDE, you may be able to generate IDE
metadata using a build plugin. Maven includes plugins for
http://maven.apache.org/plugins/maven-eclipse-plugin/[Eclipse] and
http://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 will see a "`Port already in
use`" error. STS users can use the `Relaunch` button rather than `Run` 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`. For example:

[indent=0,subs="attributes"]
----
	$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
----

It is also possible to run a packaged application with remote debugging support enabled.
This allows you to attach a debugger to your packaged application:

[indent=0,subs="attributes"]
----
	$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
	       -jar target/myproject-0.0.1-SNAPSHOT.jar
----



[[using-boot-running-with-the-maven-plugin]]
=== Using the Maven plugin
The Spring Boot Maven plugin includes a `run` goal which can be used to quickly compile
and run your application. Applications run in an exploded form just like in your IDE.

[indent=0,subs="attributes"]
----
	$ mvn spring-boot:run
----

You might also want to use the useful operating system environment variable:

[indent=0,subs="attributes"]
----
	$ export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M
----



[[using-boot-running-with-the-gradle-plugin]]
=== Using the Gradle plugin
The Spring Boot Gradle plugin also includes a `bootRun` task which can be used to run
your application in an exploded form. The `bootRun` task is added whenever you import
the `spring-boot-gradle-plugin`:

[indent=0,subs="attributes"]
----
	$ gradle bootRun
----

You might also want to use this useful operating system environment variable:

[indent=0,subs="attributes"]
----
	$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M
----



[[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
http://zeroturnaround.com/software/jrebel/[JRebel] or the
https://github.com/spring-projects/spring-loaded[Spring Loaded] project can be used. The
`spring-boot-devtools` module also includes support for quick application restarts.

See the <<using-boot-devtools>> section below 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, simply add the module dependency to your build:

.Maven
[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>
----

.Gradle
[source,groovy,indent=0,subs="attributes"]
----
	dependencies {
		compile("org.springframework.boot:spring-boot-devtools")
	}
----

NOTE: Developer tools are automatically disabled when running a fully packaged
application. If your application is launched using `java -jar` or if it's started using a
special classloader, then it is considered a "`production application`". Flagging the
dependency as optional is a best practice that prevents devtools from being transitively
applied to other modules using your project. Gradle does not support `optional`
dependencies out-of-the-box so you may want to have a look to the
{propdeps-plugin}[`propdeps-plugin`] in the meantime.

TIP: repackaged archives do not contain devtools by default. If you want to use
<<using-boot-devtools-remote,certain remote devtools feature>>, you'll 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>>
will cache compiled templates to avoid repeatedly parsing template files.
Also, Spring MVC can add HTTP caching headers to responses when serving static resources.

Whilst 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 will disable those 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 will automatically
apply sensible development-time configuration.

TIP: For a complete list of the properties that are applied see
{sc-spring-boot-devtools}/env/DevToolsPropertyDefaultsPostProcessor.{sc-ext}[DevToolsPropertyDefaultsPostProcessor].



[[using-boot-devtools-restart]]
=== Automatic restart
Applications that use `spring-boot-devtools` will 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 will be 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 will cause the classpath to be
updated and trigger a restart. In IntelliJ IDEA, building the project (`Build +->+ Make
Project`) will have the same effect.
****

[NOTE]
====
You can also start your application via the supported build plugins (i.e. Maven and
Gradle) as long as forking is enabled since DevTools need an isolated application
classloader to operate properly. Gradle and Maven do that by default when they detect
DevTools on the classpath.

====

TIP: Automatic restart works very well when used with LiveReload.
<<using-boot-devtools-livereload,See below>> for details. If you use JRebel automatic
restarts will be 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 will 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: 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.

[[using-spring-boot-restart-vs-reload]]
.Restart vs Reload
****
The restart technology provided by Spring Boot works by using two classloaders.
Classes that don't change (for example, those from third-party jars) are loaded into a
_base_ classloader. Classes that you're 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 aren't quick enough for your applications, or you encounter
classloading issues, you could consider reloading technologies such as
http://zeroturnaround.com/software/jrebel/[JRebel] from ZeroTurnaround. These work by
rewriting classes as they are loaded to make them more amenable to reloading.
https://github.com/spring-projects/spring-loaded[Spring Loaded] provides another option,
however it doesn't support as many frameworks and it isn't commercially supported.
****



[[using-boot-devtools-restart-exclude]]
==== Excluding resources
Certain resources don't necessarily need to trigger a restart when they are changed. For
example, Thymeleaf templates can just be edited in-place. By default changing resources
in `/META-INF/maven`, `/META-INF/resources`, `/resources`, `/static`, `/public` or
`/templates` will not trigger a restart but will 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:

[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.


[[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 above>> to control whether changes
beneath the additional paths will trigger a full restart or just a
<<using-boot-devtools-livereload, live reload>>.



[[using-boot-devtools-restart-disable]]
==== Disabling restart
If you don't want to use the restart feature you can disable it using the
`spring.devtools.restart.enabled` property. In most cases you can set this in your
`application.properties` (this will still initialize the restart classloader but it won't
watch for file changes).

If you need to _completely_ disable restart support, for example, because it doesn't work
with a specific library, you need to set a `System` property before calling
`SpringApplication.run(...)`. For example:

[source,java,indent=0]
----
	public static void main(String[] args) {
		System.setProperty("spring.devtools.restart.enabled", "false");
		SpringApplication.run(MyApp.class, args);
	}
----



[[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 this 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 will only occur if Devtools has
detected it has to do something. The trigger file could be updated manually, or via an IDE
plugin.

To use a trigger file use the `spring.devtools.restart.trigger-file` property.

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 in the <<using-spring-boot-restart-vs-reload>> section above, restart
functionality is implemented by using two classloaders. For most applications this
approach works well, however, sometimes it can cause classloading issues.

By default, any open project in your IDE will be loaded using the "`restart`" classloader,
and any regular `.jar` file will be loaded using the "`base`" classloader. If you work on
a multi-module project, and not each module is imported into your IDE, you may need to
customize things. To do this you can create a `META-INF/spring-devtools.properties` file.

The `spring-devtools.properties` file can contain `restart.exclude.` and
`restart.include.` prefixed properties. 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 will be applied to the classpath.

For example:

[source,properties,indent=0]
----
	restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar
	restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar
----

NOTE: All property keys must be unique. As long as a property starts with
`restart.include.` or `restart.exclude.` it will be considered.

TIP: All `META-INF/spring-devtools.properties` from the classpath will be 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 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 will 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].

If you don't 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 will have 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 will 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:

.~/.spring-boot-devtools.properties
[source,properties,indent=0]
----
	spring.devtools.reload.trigger-file=.reloadtrigger
----



[[using-boot-devtools-remote]]
=== Remote applications
The Spring Boot developer tools are not just 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:

[source,xml,indent=0,subs="verbatim,quotes,attributes"]
----
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludeDevtools>false</excludeDevtools>
				</configuration>
			</plugin>
		</plugins>
	</build>
----

Then you need to set a `spring.devtools.remote.secret` property, for 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.

Remote devtools support is provided in two parts; there is 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` using the same classpath as
the remote project that you're connecting to. The _non-option_ argument passed to the
application should be the remote URL that you are connecting to.

For example, if you are using Eclipse or STS, and you have a project named `my-app` that
you've 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).

A running remote client will look like this:

[indent=0,subs="attributes"]
----
	  .   ____          _                                              __ _ _
	 /\\ / ___'_ __ _ _(_)_ __  __ _          ___               _      \ \ \ \
	( ( )\___ | '_ | '_| | '_ \/ _` |        | _ \___ _ __  ___| |_ ___ \ \ \ \
	 \\/  ___)| |_)| | | | | || (_| []::::::[]   / -_) '  \/ _ \  _/ -_) ) ) ) )
	  '  |____| .__|_| |_|_| |_\__, |        |_|_\___|_|_|_\___/\__\___|/ / / /
	 =========|_|==============|___/===================================/_/_/_/
	 :: Spring Boot Remote :: {spring-boot-version}

	2015-06-10 18:25:06.632  INFO 14938 --- [           main] o.s.b.devtools.RemoteSpringApplication   : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code/spring-boot-samples/spring-boot-sample-devtools)
	2015-06-10 18:25:06.671  INFO 14938 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy
	2015-06-10 18:25:07.043  WARN 14938 --- [           main] o.s.b.d.r.c.RemoteClientConfiguration    : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'.
	2015-06-10 18:25:07.074  INFO 14938 --- [           main] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
	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.

TIP: It's 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.



[[using-boot-devtools-remote-update]]
==== Remote update
The remote client will monitor your application classpath for changes in the same way as
the <<using-boot-devtools-restart,local restart>>. Any updated resource will be pushed
to the remote application and _(if required)_ trigger a restart. This can be quite helpful
if you are iterating on a feature that uses a cloud service that you don't 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 won't be pushed to the remote server.



[[using-boot-devtools-remote-debugtunnel]]
==== Remote debug tunnel
Java remote debugging is useful when diagnosing issues on a remote application.
Unfortunately, it's not always possible to enable remote debugging when your application
is deployed outside of your data center. Remote debugging can also be tricky to setup if
you are using a container based technology such as Docker.

To help work around these limitations, devtools supports tunneling of remote debug traffic
over HTTP. The remote client provides a local server on port `8000` that you can attach
a remote debugger to. Once a connection is established, debug traffic is sent over HTTP
to the remote application. You can use the `spring.devtools.remote.debug.local-port`
property if you want to use a different port.

You'll need to ensure that your remote application is started with remote debugging
enabled. Often this can be achieved by configuring `JAVA_OPTS`. For example, with
Cloud Foundry you can add the following to your `manifest.yml`:

[source,yaml,indent=0]
----
	---
		env:
			JAVA_OPTS: "-Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n"
----

TIP: Notice that you don't need to pass an `address=NNNN` option to `-Xrunjdwp`. If
omitted Java will simply pick a random free port.

NOTE: Debugging a remote service over the Internet can be slow and you might need to
increase timeouts in your IDE. For example, in Eclipse you can select `Java` -> `Debug`
from `Preferences...` and change the `Debugger timeout (ms)` to a more suitable value
(`60000` works well in most situations).

WARNING: When using the remote debug tunnel with IntelliJ IDEA, all breakpoints must be
configured to suspend the thread rather than the VM. By default, breakpoints in IntelliJ
IDEA suspend the entire VM rather than only suspending the thread that hit the
breakpoint. This has the unwanted side-effect of suspending the thread that manages the
remote debug tunnel, causing your debugging session to freeze. When using the remote
debug tunnel with IntelliJ IDEA, all breakpoints should be configured to suspend the
thread rather than the VM. Please see
https://youtrack.jetbrains.com/issue/IDEA-165769[IDEA-165769] for further details.



[[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.

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 have good understanding of how you can use Spring Boot along with 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.
