Remove duplicate documentation

Remove README files that have been since been migrated to the reference
documentation. Also updated remaining markdown files to asciidoctor to
save having a mix of different formats.

Fixed gh-503
This commit is contained in:
Phillip Webb 2014-03-16 23:00:12 -07:00
parent d0275b4734
commit c5ee3c7eba
24 changed files with 285 additions and 4416 deletions

View File

@ -1,58 +1,68 @@
# Contributing to Spring Boot
= Contributing to Spring Boot
Spring Boot is released under the non-restrictive Apache 2.0 license. If you would like
to contribute something, or simply want to hack on the code this document should help
you get started.
## Sign the Contributor License Agreement
== Sign the Contributor License Agreement
Before we accept a non-trivial patch or pull request we will need you to sign the
[contributor's agreement](https://support.springsource.com/spring_committer_signup).
Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we
can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join
the core team, and given the ability to merge pull requests.
https://support.springsource.com/spring_committer_signup[contributor's agreement].
Signing the contributor's agreement does not grant anyone commit rights to the main
repository, but it does mean that we can accept your contributions, and you will get an
author credit if we do. Active contributors might be asked to join the core team, and
given the ability to merge pull requests.
## Code Conventions and Housekeeping
== Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be
added after the original pull request but before a merge.
None of these is essential for a pull request, but they will all help. They can also be added after the original pull
request but before a merge.
* Use the Spring Framework code format conventions. Import `eclipse-code-formatter.xml` from the `eclipse` folder of the project
if you are using Eclipse. If using IntelliJ, copy `spring-intellij-code-style.xml` to `~/.IntelliJIdea*/config/codestyles`
and select spring-intellij-code-style from Settings -> Code Styles.
* Make sure all new .java files to have a simple Javadoc class comment with at least an @author tag identifying you, and
preferably at least a paragraph on what the class is for.
* Add the ASF license header comment to all new .java files (copy from existing files in the project)
* Add yourself as an @author to the .java files that you modify substantially (more than cosmetic changes).
* Use the Spring Framework code format conventions. Import `eclipse-code-formatter.xml`
from the `eclipse` folder of the project if you are using Eclipse. If using IntelliJ,
copy `spring-intellij-code-style.xml` to `~/.IntelliJIdea*/config/codestyles` and select
spring-intellij-code-style from Settings -> Code Styles.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is
for.
* Add the ASF license header comment to all new `.java` files (copy from existing files
in the project)
* Add yourself as an `@author` to the .java files that you modify substantially (more
than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well - someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project).
* A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or
other target branch in the main project).
## Working with the code
== Working with the code
If you don't have an IDE preference we would recommend that you use
[Spring Tools Suite](http://www.springsource.com/developer/sts) or
[Eclipse](http://eclipse.org) when working with the code. We use the
[m2eclipe](http://eclipse.org/m2e/) eclipse plugin for maven support. Other IDEs
and tools should also work without issue.
http://www.springsource.com/developer/sts[Spring Tools Suite] or
http://eclipse.org[Eclipse] when working with the code. We use the
http://eclipse.org/m2e/[m2eclipe] eclipse plugin for maven support. Other IDEs and tools
should also work without issue.
### Building from source
=== Building from source
To build the source you will need to install
[Apache Maven](http://maven.apache.org/run-maven/index.html) v3.0 or above.
http://maven.apache.org/run-maven/index.html[Apache Maven] v3.0 or above.
#### Default build
==== Default build
The project can be built from the root directory using the standard maven command:
[indent=0]
----
$ mvn clean install
----
> **NOTE:** You may need to increase the amount of memory available to Maven by setting
> a `MAVEN_OPTS` environment variable with the value `-Xmx512m -XX:MaxPermSize=128m`
NOTE: You may need to increase the amount of memory available to Maven by setting
a `MAVEN_OPTS` environment variable with the value `-Xmx512m -XX:MaxPermSize=128m`
If you are rebuilding often, you might also want to skip the tests until you are ready
to submit a pull request:
[indent=0]
----
$ mvn clean install -DskipTests
----
#### Full Build
==== Full Build
Multi-module Maven builds cannot directly include maven plugins that are part of the
reactor unless they have previously been built. Unfortunately this restriction causes
some compilations for Spring Boot as we include a maven plugin and use it within the
@ -71,24 +81,30 @@ can be referenced during the full build. It also generates a `settings.xml` file
enables a `snapshot`, `milestone` or `release` profiles based on the version being
build. To prepare the build, from the root directory use:
[indent=0]
----
$ mvn -P snapshot,prepare install
----
> **NOTE:** You may notice that preparing the build also changes the
> `spring-boot-starter-parent` POM. This is required for our release process to work
> correctly.
NOTE: You may notice that preparing the build also changes the
`spring-boot-starter-parent` POM. This is required for our release process to work
correctly.
2) Run the full build
Once the build has been prepared, you can run a full build using the following commands:
[indent=0]
----
$ cd spring-boot-full-build
$ mvn -s ../settings.xml -P full clean install
----
We generate more artifacts when running the full build (such as Javadoc jars), so you
may find the process a little slower than the standard build.
### Importing into eclipse with m2eclipse
We recommend the [m2eclipe](http://eclipse.org/m2e/) eclipse plugin when working with
=== Importing into eclipse with m2eclipse
We recommend the http://eclipse.org/m2e/[m2eclipe] eclipse plugin when working with
eclipse. If you don't already have m2eclipse installed it is available from the "eclipse
marketplace".
@ -98,30 +114,33 @@ work with m2eclipse, we provide an additional eclipse plugin that you can instal
* Select `Install new software` from the `help` menu
* Click `Add...` to add a new repository
* Click the `Archive...` button
* Select `org.eclipse.m2e.maveneclipse.site-0.0.1-SNAPSHOT-site.zip`
from the `eclipse` folder in this checkout
* Select `org.eclipse.m2e.maveneclipse.site-0.0.1-SNAPSHOT-site.zip` from the `eclipse`
folder in this checkout
* Install "Maven Integration for the maven-eclipse-plugin"
_NOTE: This plugin is optional. Projects can be imported without the plugin, your code
NOTE: This plugin is optional. Projects can be imported without the plugin, your code
changes just won't be automatically formatted._
With the requisite eclipse plugins installed you can select
`import existing maven projects` from the `file` menu to import the code. You will
need to import the root `spring-boot` pom and the `spring-boot-samples` pom separately.
### Importing into eclipse without m2eclipse
=== Importing into eclipse without m2eclipse
If you prefer not to use m2eclipse you can generate eclipse project meta-data using the
following command:
[indent=0]
----
$ mvn eclipse:eclipse
----
The generated eclipse projects can be imported by selecting `import existing projects`
from the `file` menu.
### Importing into other IDEs
=== Importing into other IDEs
Maven is well supported by most Java IDEs. Refer to you vendor documentation.
### Integration tests
== Integration tests
The sample application are used as integration tests during the build (when you
`mvn install`). Due to the fact that they make use of the `spring-boot-maven-plugin`
they cannot be called directly, and so instead are launched via the

214
README.adoc Normal file
View File

@ -0,0 +1,214 @@
= Spring Boot image:https://travis-ci.org/spring-projects/spring-boot.png?branch=master["Build Status", link="https://travis-ci.org/spring-projects/spring-boot"]
:docs: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference
Spring Boot makes it easy to create Spring-powered, production-grade applications and
services with absolute minimum fuss. It takes an opinionated view of the Spring platform
so that new and existing users can quickly get to the bits they need.
You can use Spring Boot to create stand-alone Java applications that can be started 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
(e.g. embedded servers, security, metrics, health checks, externalized configuration)
* Absolutely no code generation and no requirement for XML configuration
== Installation and Getting Started
The {docs}/htmlsingle/[reference documentation] includes detailed
{docs}/htmlsingle/#getting-started-installing-spring-boot[installation instructions]
as well as a comprehensive {docs}/htmlsingle/#getting-started-first-application[``getting
started''] guide. Documentation is published in {docs}/htmlsingle/[HTML],
{docs}/pdf/spring-boot-reference.pdf[PDF] and {docs}/epub/spring-boot-reference.epub[EPUB]
formats.
Here is a quick teaser of a Spring Boot application:
[source,java,indent=0]
----
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@Controller
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
----
== Getting help
Having trouble with Spring Boot, We'd like to help!
* Check the {docs}/htmlsingle/[reference documentation], especially the
{docs}/htmlsingle/#howto[How-to's] -- they provide solutions to the most common
questions.
* Learn the Spring basics -- Spring Boot is builds on many other Spring projects, check
the http://spring.io[spring.io] web-site for a wealth of reference documentation. If
you are just starting out with Spring, try one of the http://spring.io/guides[guides].
* Ask a questions - we monitor http://stackoverflow.com[stackoverflow.com] for questions
tagged with http://stackoverflow.com/tags/spring-boot[`spring-boot`].
* Report bugs with Spring Boot at https://github.com/spring-projects/spring-boot/issues.
== Building from Source
You don't need to build from source to use Spring Boot (binaries in
http://repo.spring.io[repo.spring.io], but if you want to try out the latest and greatest,
Spring Boot can be http://maven.apache.org/run-maven/index.html[built with maven]
v3.0.5 or above.
[indent=0]
----
$ mvn clean install
----
NOTE: You may need to increase the amount of memory available to Maven by setting
a `MAVEN_OPTS` environment variable with the value `-Xmx512m -XX:MaxPermSize=128m`
_Also see link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] if you wish to submit pull requests,
and in particular please fill out the
https://support.springsource.com/spring_committer_signup[Contributor's Agreement]
before your first change however trivial. (Or if you filed such an agreement already for
another project just mention that in your pull request.)_
== Modules
There are a number of modules in Spring Boot, here is a quick overview:
=== spring-boot
The main library providing features that support the other parts of Spring Boot,
these include:
* The `SpringApplication` class, providing static convenience methods that make it easy
to write a stand-alone Spring Application. Its sole job is to create and refresh an
appropriate Spring `ApplicationContext`
* Embedded web applications with a choice of container (Tomcat or Jetty for now)
* First class externalized configuration support
* Convenience `ApplicationContext` initializers, including support for sensible logging
defaults
=== spring-boot-autoconfigure
Spring Boot can configure large parts of common applications based on the content
of their classpath. A single `@EnableAutoConfiguration` annotation triggers
auto-configuration of the Spring context.
Auto-configuration attempts to deduce which beans a user might need. For example, If
`HSQLDB` is on the classpath, and the user has not configured any database connections,
then they probably want an in-memory database to be defined. Auto-configuration will
always back away as the user starts to define their own beans.
=== spring-boot-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.
=== spring-boot-cli
The Spring command line application compiles and runs Groovy source, making it super
easy to write the absolute minimum of code to get an application running. Spring CLI
can also watch files, automatically recompiling and restarting when they change.
=== spring-boot-actuator
Spring Boot Actuator provides additional auto-configuration to decorate your application
with features that make it instantly deployable and supportable in production. For
instance if you are writing a JSON web service then it will provide a server, security,
logging, externalized configuration, management endpoints, an audit abstraction, and
more. If you want to switch off the built in features, or extend or replace them, it
makes that really easy as well.
=== spring-boot-loader
Spring Boot Loader provides the secret sauce that allows you to build a single jar file
that can be launched using `java -jar`. Generally you will not need to use
`spring-boot-loader` directly, but instead work with the
link:spring-boot-tools/spring-boot-gradle-plugin[Gradle] or
link:spring-boot-tools/spring-boot-maven-plugin[Maven] plugin.
== Samples
Groovy samples for use with the command line application are available in
link:spring-boot-cli/samples[spring-boot-cli/samples]. To run the CLI samples type
`spring run <sample>.groovy` from samples directory.
Java samples are available in link:spring-boot-samples[spring-boot-samples] and should
be built with maven and run by invoking `java -jar target/<sample>.jar`. The following
java samples are provided:
* link:spring-boot-samples/spring-boot-sample-simple[spring-boot-sample-simple]
-- A simple command line application
* link:spring-boot-samples/spring-boot-sample-tomcat[spring-boot-sample-tomcat]
-- Embedded Tomcat
* link:spring-boot-samples/spring-boot-sample-jetty[spring-boot-sample-jetty]
-- Embedded Jetty
* link:spring-boot-samples/spring-boot-sample-actuator[spring-boot-sample-actuator]
-- Simple REST service with production features
* link:spring-boot-samples/spring-boot-sample-actuator-ui[spring-boot-sample-actuator-ui]
-- A web UI example with production features
* link:spring-boot-samples/spring-boot-sample-web-ui[spring-boot-sample-web-ui]
-- A thymeleaf web application
* link:spring-boot-samples/spring-boot-sample-web-static[spring-boot-sample-web-static]
-- A web application service static files
* link:spring-boot-samples/spring-boot-sample-batch[spring-boot-sample-batch]
-- Define and run a Batch job in a few lines of code
* link:spring-boot-samples/spring-boot-sample-data-jpa[spring-boot-sample-data-jpa]
-- Spring Data JPA + Hibernate + HSQLDB
* link:spring-boot-samples/spring-boot-sample-integration[spring-boot-sample-integration]
-- A spring integration application
* link:spring-boot-samples/spring-boot-sample-profile[spring-boot-sample-profile]
-- example showing Spring's `@profile` support
* link:spring-boot-samples/spring-boot-sample-traditional[spring-boot-sample-traditional]
-- shows more traditional WAR packaging (but also executable using `java -jar`)
* link:spring-boot-samples/spring-boot-sample-xml[spring-boot-sample-xml]
-- Example show how Spring Boot can be mixed with traditional XML configuration (we
generally recommend using Java `@Configuration` whenever possible)
== Guides
The http://spring.io/[spring.io] site contains several guides that show how to use Spring
Boot step-by-step:
* http://spring.io/guides/gs/spring-boot/[Building an Application with Spring Boot] is a
very basic guide that shows you how to create a simple application, run it and add some
management services.
* http://spring.io/guides/gs/actuator-service/[Building a RESTful Web Service with Spring
Boot Actuator] is a guide to creating a REST web service and also shows how the server
can be configured.
* http://spring.io/guides/gs/convert-jar-to-war/[Converting a Spring Boot JAR Application
to a WAR] shows you how to run applications in a web server as a WAR file.

400
README.md
View File

@ -1,400 +0,0 @@
# Spring Boot [![Build Status](https://travis-ci.org/spring-projects/spring-boot.png?branch=master)](https://travis-ci.org/spring-projects/spring-boot)
Spring Boot makes it easy to create Spring-powered, production-grade applications and
services with absolute minimum fuss. It takes an opinionated view of the Spring platform
so that new and existing users can quickly get to the bits they need.
You can use Spring Boot to create stand-alone Java applications that can be started 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
(e.g. embedded servers, security, metrics, health checks, externalized configuration)
* Absolutely no code generation and no requirement for XML configuration
A good place for further reading is the
[compendium of micro HOWTO guides](docs/howto.md) covering many common
use cases.
## Spring Boot CLI
The Spring Boot CLI is a command line tool that can be used if you want to quickly
prototype with Spring. It allows you to run [Groovy](http://groovy.codehaus.org/) scripts,
which means that you have a familiar Java-like syntax, without so much boilerplate code.
You don't need to use the CLI to work with Spring Boot but it's definitely the quickest
way to get a Spring application off the ground.
> **Note:** If you don't want to use the CLI,
> [jump ahead to the Java example](#quick-start-java-example).
### Installing the CLI
You need [Java SDK v1.6](http://www.java.com) or higher to run the command line tool
(there are even some issues with the `1.7.0_25` build of openjdk, so stick to earlier
builds or use `1.6` for preference). You should check your current Java installation
before you begin:
$ java -version
### Manual installation
You can download the Spring CLI distribution from the Spring software repository:
* [spring-boot-cli-1.0.0.RC4-bin.zip](http://repo.spring.io/milestone/org/springframework/boot/spring-boot-cli/1.0.0.RC4/spring-boot-cli-1.0.0.RC4-bin.zip)
* [spring-boot-cli-1.0.0.RC4-bin.tar.gz](http://repo.spring.io/milestone/org/springframework/boot/spring-boot-cli/1.0.0.RC4/spring-boot-cli-1.0.0.RC4-bin.tar.gz)
Cutting edge [snapshot distributions](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/)
are also available.
Once downloaded, follow the
[INSTALL](spring-boot-cli/src/main/content/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,
or alternatively you can use `java -jar` with the `.jar` file (the
script helps you to be sure that the classpath is set correctly).
### Installation with GVM
GVM (the Groovy Environment Manager) can be used for managing multiple
versions of verious Groovy and Java binary packages, including Groovy
itself and the Spring Boot CLI. Get `gvm` from
[the gvm home page](http://gvmtool.net) and install Spring Boot with
$ gvm install springboot
$ spring --version
Spring Boot v1.0.0.RC4
> **Note:** If you are developing features for the CLI and want easy access to the version you just built, follow these extra instructions.
$ gvm install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-1.0.0.BUILD-SNAPSHOT-bin/spring-1.0.0.BUILD-SNAPSHOT/
$ gvm use springboot dev
$ spring --version
Spring CLI v1.0.0.BUILD-SNAPSHOT
This will install a local instance of `spring` called the `dev` instance inside your gvm repository. It points at your target build location, so every time you rebuild Spring Boot, `spring` will be up-to-date.
You can see it by doing this:
$ gvm ls springboot
```
================================================================================
Available Springboot Versions
================================================================================
> + dev
* 1.0.0.RC4
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
```
### OSX Homebrew installation
If you are on a Mac and using [homebrew](http://brew.sh/), all you need to do to install
the Spring Boot CLI is:
```
$ brew tap pivotal/tap
$ brew install springboot
```
Homebrew will install `spring` to `/usr/local/bin`. Now you can jump right to a
[quick start example](#quick-start-script-example).
> **Note:** If you don't see the formula, you're installation of brew might be
> out-of-date. Just execute `brew update` and try again.
### Quick start script example
Here's a really simple web application. Create a file called `app.groovy`:
```groovy
@Controller
class ThisWillActuallyRun {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!"
}
}
```
Then run it from a shell:
```
$ spring run app.groovy
```
> **Note:** It will take some time when you first run the application as dependencies
> are downloaded, subsequent runs will be much quicker.
Open [http://localhost:8080](http://localhost:8080) in your favorite web browser and you
should see the following output:
> Hello World!
## Spring Boot with Java
If you don't want to use the command line tool, or you would rather work using Java and
an IDE you can. Here is how you build the same example using Java.
### Quick start Maven POM
You will need to install [Apache Maven](http://maven.apache.org/) v3.0.5 or above to build
this example.
Create a `pom.xml` to import the appropriate Spring Boot starters:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.0.RC4</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable JAR -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- Allow access to Spring milestones and snapshots -->
<!-- (you don't need this if you are using anything after 1.0.0.RELEASE) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
```
> **Note:** If you prefer [Gradle](http://www.gradle.org) as your build system, we provide
> a [plugin](spring-boot-tools/spring-boot-gradle-plugin/README.md) that can help you
> package an executable JAR.
More detail about the Maven plugin, and how to build a Spring Boot
project with Maven is available in the [starter docs](spring-boot-starters/README.md).
<span id="quick-start-java-example"></span>
### Quick start Java example
Here is the main class for a simple web application (just save the content to
`src/main/java/SampleController.java`):
```java
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
```
Other than import statements, the main difference between this
example and the earlier Groovy script is the `main()` method that calls
`SpringApplication` and the `@EnableAutoConfiguration` annotation.
You can run this application by building a `jar` and executing it:
```
$ mvn package
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
```
Open [http://localhost:8080](http://localhost:8080) in your favorite web browser and you
should see the following output:
> Hello World!
## Building Spring Boot from source
You don't need to build from source to use Spring Boot (it's in
[repo.spring.io](http://repo.spring.io)), but if you want to try out the
latest and greatest, Spring Boot can be
[built with maven](http://maven.apache.org/run-maven/index.html) v3.0.5 or above.
$ mvn clean install
> **NOTE:** You may need to increase the amount of memory available to Maven by setting
> a `MAVEN_OPTS` environment variable with the value `-Xmx512m -XX:MaxPermSize=128m`
_Also see [CONTRIBUTING.md](CONTRIBUTING.md) if you wish to submit
pull requests, and in particular please fill out the
[Contributor's Agreement](https://support.springsource.com/spring_committer_signup)
before your first change however trivial. (Or if you filed such an
agreement already for another project just mention that in your pull
request.)_
## Modules
There are a number of modules in Spring Boot, if you want learn more about each one
please refer to the appropriate README.md file:
> **Note:** We are currently still working on documentation for Spring Boot.
### spring-boot
The main library providing features that support the other parts of Spring Boot,
these include:
* The `SpringApplication` class, providing static convenience methods that make it easy
to write a stand-alone Spring Application. Its sole job is to create and refresh an
appropriate Spring `ApplicationContext`
* Embedded web applications with a choice of container (Tomcat or Jetty for now)
* First class externalized configuration support
* Convenience `ApplicationContext` initializers, including support for sensible logging
defaults
_See [spring-boot/README.md](spring-boot/README.md)._
### spring-boot-autoconfigure
Spring Boot can configure large parts of common applications based on the content
of their classpath. A single `@EnableAutoConfiguration` annotation triggers
auto-configuration of the Spring context.
Auto-configuration attempts to deduce which beans a user might need. For example, If
`HSQLDB` is on the classpath, and the user has not configured any database connections,
then they probably want an in-memory database to be defined. Auto-configuration will
always back away as the user starts to define their own beans.
_See [spring-boot-autoconfigure/README.md](spring-boot-autoconfigure/README.md)._
### spring-boot-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.
_See [spring-boot-starters/README.md](spring-boot-starters/README.md)._
### spring-boot-cli
The Spring command line application compiles and runs Groovy source, making it super
easy to write the absolute minimum of code to get an application running. Spring CLI
can also watch files, automatically recompiling and restarting when they change.
*See [spring-boot-cli/README.md](spring-boot-cli/README.md).*
### spring-boot-actuator
Spring Boot Actuator provides additional auto-configuration to decorate your application
with features that make it instantly deployable and supportable in production. For
instance if you are writing a JSON web service then it will provide a server, security,
logging, externalized configuration, management endpoints, an audit abstraction, and
more. If you want to switch off the built in features, or extend or replace them, it
makes that really easy as well.
_See [spring-boot-actuator/README.md](spring-boot-actuator/README.md)._
### spring-boot-loader
Spring Boot Loader provides the secret sauce that allows you to build a single jar file
that can be launched using `java -jar`. Generally you will not need to use
`spring-boot-loader` directly, but instead work with the
[Gradle](spring-boot-tools/spring-boot-gradle-plugin/README.md) or
[Maven](spring-boot-tools/spring-boot-maven-plugin/README.md) plugin.
_See [spring-boot-loader/README.md](spring-boot-tools/spring-boot-loader/README.md)._
## Samples
Groovy samples for use with the command line application are available in
[spring-boot-cli/samples](spring-boot-cli/samples). To run the CLI samples type
`spring run <sample>.groovy` from samples directory.
Java samples are available in [spring-boot-samples](spring-boot-samples) and should
be built with maven and run by invoking `java -jar target/<sample>.jar`. The following java
samples are provided:
* [spring-boot-sample-simple](spring-boot-samples/spring-boot-sample-simple) -
A simple command line application
* [spring-boot-sample-tomcat](spring-boot-samples/spring-boot-sample-tomcat) -
Embedded Tomcat
* [spring-boot-sample-jetty](spring-boot-samples/spring-boot-sample-jetty) -
Embedded Jetty
* [spring-boot-sample-actuator](spring-boot-samples/spring-boot-sample-actuator) -
Simple REST service with production features
* [spring-boot-sample-actuator-ui](spring-boot-samples/spring-boot-sample-actuator-ui) -
A web UI example with production features
* [spring-boot-sample-web-ui](spring-boot-samples/spring-boot-sample-web-ui) -
A thymeleaf web application
* [spring-boot-sample-web-static](spring-boot-samples/spring-boot-sample-web-static) -
A web application service static files
* [spring-boot-sample-batch](spring-boot-samples/spring-boot-sample-batch) -
Define and run a Batch job in a few lines of code
* [spring-boot-sample-data-jpa](spring-boot-samples/spring-boot-sample-data-jpa) -
Spring Data JPA + Hibernate + HSQLDB
* [spring-boot-sample-integration](spring-boot-samples/spring-boot-sample-integration) -
A spring integration application
* [spring-boot-sample-profile](spring-boot-samples/spring-boot-sample-profile) -
example showing Spring's `@profile` support
* [spring-boot-sample-traditional](spring-boot-samples/spring-boot-sample-traditional) -
shows more traditional WAR packaging
(but also executable using `java -jar`)
* [spring-boot-sample-xml](spring-boot-samples/spring-boot-sample-xml) -
Example show how Spring Boot can be mixed with traditional XML configuration (we
generally recommend using Java `@Configuration` whenever possible)
## Guides
The [spring.io](http://spring.io/) site contains several guides that show how to use Spring Boot step-by-step:
* [Building an Application with Spring
Boot](http://spring.io/guides/gs/spring-boot/) is a very basic guide
that shows you how to create a simple application, run it and add some
management services.
* [Building a RESTful Web Service with Spring Boot Actuator](http://spring.io/guides/gs/actuator-service/)
is a guide to creating a REST web service and also shows how the server can be configured.
* [Converting a Spring Boot JAR Application to a WAR](http://spring.io/guides/gs/convert-jar-to-war/) shows you how to run applications in a
web server as a WAR file.

4
docs/README.adoc Normal file
View File

@ -0,0 +1,4 @@
= NOTE
Documentation can now be found in the `spring-boot-docs` project. This folder will be
removed at a future date.

View File

@ -1,151 +0,0 @@
# Docs without a home as yet :(
|Feature |Implementation |Notes |
|---|---|---|
|Launch Spring from Java main |SpringApplication | Plenty of convenience methods and customization opportunities |
|Server |Tomcat or Jetty | |
|Logging |Logback, Log4j or JDK | Sensible defaults configurations. |
|Externalized configuration | Properties or YAML | Support for Spring profiles. Bind automatically to @Bean. |
For a quick introduction and to get started quickly with a new
project, carry on reading.
# Getting Started
You will need Java (6 at least) and a build tool (Maven is what we use
below, but you are more than welcome to use gradle). These can be
downloaded or installed easily in most operating systems. For Ubuntu:
$ sudo apt-get install openjdk-6-jdk maven
<!--FIXME: short instructions for Mac.-->
## A basic project
If you are using Maven create a really simple `pom.xml` with 2 dependencies:
`pom.xml`
```
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myproject</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<start-class>com.mycompany.Application</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-starter-parent</artifactId>
<version>{{project.version}}</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-starter</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-package-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
If you like Gradle, that's fine, and you will know what to do with
those dependencies. The one dependency adds Spring Boot.Config auto
configuration and the Tomcat container to your application. If you
prefer Jetty you can just add the embedded Jetty jars to your
classpath instead of Tomcat.
Now write a simple main class
`Application.java`
```
package com.mycompany;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
You should be able to run it already:
$ mvn package
$ java -jar target/myproject-1.0.0-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
Spring Bootstrap
2013-07-19 17:13:51.673 INFO 18937 --- [ main] com.mycompany.Application ...
... <logs showing application starting up>
It doesn't do anything yet, but that's because all we did is start a
Spring `ApplicationContext` and let it close when the JVM stopped.
To make it do something a little bit more interesting you could bind
some command line arguments to the application:
`Application.java`
```
@Configuration
@ConfigurationProperties
@EnableConfigurationProperties
public class Application {
private String message;
@Override
public void run(String... args) throws Exception {
System.err.println(message);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
```
The `@ConfigurationProperties` annotation binds the Spring
`Environment` (including command line arguments) to the `Application`
instance, and `CommandLineRunner` is a marker interface for anything
you want to be executed after the content is started. So run it
again and you will see the message:
```
$ mvn package
$ java -jar target/myproject-1.0.0-SNAPSHOT.jar --message="Hello World"
...
Hello World
```
To add more features, add some `@Bean` definitions to your
`Application` class.

View File

@ -1,105 +0,0 @@
# Core
spring:
# The name of the application
application.name: myapp
# The name of the main config file, default is application
config.name: application
# Profiles that should be active
profiles.active:
# Configuration for SpringApplication setters
main:
web-environment: true
show-banner:false
log-startup-info: false
# ...
# Server settings (ServerProperties)
server:
port: 8080
address: 127.0.0.1
sessionTimeout: 30
contextPath: /root
# Tomcat specifics
tomcat:
accessLogEnabled: false
protocolHeader: x-forwarded-proto
remoteIpHeader: x-forwarded-for
basedir:
backgroundProcessorDelay: 30 # secs
---
# Auto-Configure
spring:
messages:
basename: messages
batch:
schema: classpath:org/springframework/batch/core/schema-@@platform@@.sql
database:
schema: classpath*:schema-<platform>.sql
platform: all
datasource:
driverClassName
url:
username: sa
password
max-active: 8
max-idle: 8
test-on-borrow
test-on-return
validation-query
jpa:
open-in-view:
show-sql:
database-platform:
generate-ddl:
properties:
hibernate:
naming-strategy:
cache-provider:
ddl-auto:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
cache: true
view:
prefix:
suffix:
# actuator
endpoints:
beans:
path: /beans
sensitive: false
dump:
env
health
info
metrics
shutdown
trace
# (ManagementServerProperties)
management:
port:
# (SecurityProperties)
security:
basic:
enabled: true

View File

@ -1,53 +0,0 @@
# Spring Boot 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 autoconfig report in your application for more details of
which fetaures are switched on in that specific use case (start the
app with "--debug" or "-Ddebug", or in an Actuator app go to
"/autoconfig").
(Auto-generated from `classpath*:/META-INF/spring.factories`.)
| Configuration Class | Links | Project |
|---|---|---|
| [MessageSourceAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/MessageSourceAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [PropertyPlaceholderAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [RabbitAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [AopAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [BatchAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [JpaRepositoriesAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/JpaRepositoriesAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/data/JpaRepositoriesAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [MongoRepositoriesAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/MongoRepositoriesAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/data/MongoRepositoriesAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [MongoTemplateAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/MongoTemplateAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/data/MongoTemplateAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [DataSourceAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [DataSourceTransactionManagerAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [JmsTemplateAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsTemplateAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/jms/JmsTemplateAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [JmxAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [DeviceResolverAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [MongoAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [HibernateJpaAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [ReactorAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [RedisAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/redis/RedisAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/redis/RedisAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [SecurityAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/security/SecurityAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [ThymeleafAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [DispatcherServletAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [EmbeddedServletContainerAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [HttpMessageConvertersAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [MultipartAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [ServerPropertiesAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [WebSocketAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.html) | [spring-boot-autoconfigure](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure) |
| [AuditAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [CrshAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/CrshAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [EndpointAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [EndpointMBeanExportAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [EndpointWebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [ErrorMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [JolokiaAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [ManagementSecurityAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementSecurityAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/ManagementSecurityAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [ManagementServerPropertiesAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [MetricFilterAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [MetricRepositoryAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [TraceRepositoryAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |
| [TraceWebFilterAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfiguration.java) | [javadoc](http://docs.spring.io/spring-boot/docs/1.0.0.RC4/api/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfiguration.html) | [spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator) |

View File

@ -1,1334 +1,10 @@
# How Do I Do That With Spring Boot?
Here is a starting point for a potentially large collection of micro
HOWTO guides. If you want to add a placeholder for a question without
an answer, put it at the top (at header level 2) and we can fill in
the gaps later.
**The How-to is now part of the reference documentation.**
### General Advice and Other Sources of Information
There is a really useful `AutoConfigurationReport` available in any
Spring Boot `ApplicationContext`. You will see it automatically if a
context fails to start, and also if you enable DEBUG logging for
Spring Boot. If you use the Actuator there is also an endpoint
`/autoconfig` that renders the report in JSON. Use that to debug the
application and see what features have been added (and which not) by
Spring Boot at runtime. Also [see here](./autoconfig.md) for a list of
auto configuration classes with links.
Many more questions can be answered by looking at the source code and
Javadocs. Some rules of thumb:
* Look for classes called `*AutoConfiguration` and read their sources,
in particular the `@Conditional*` annotations to find out what
features they enable and when. Add "--debug" to the command line or
a System property `-Ddebug` to get a printout on the console of all
the autoconfiguration decisions that were made in your app. In a
running Actuator app look at the "/autoconfig" endpoint (or the JMX
equivalent) for the same information.
* Look for classes that are `@ConfigurationProperties`
(e.g. [`ServerProperties`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java?source=c))
and read from there the available external configuration
options. The `@ConfigurationProperties` has a `name` attribute which
acts as a prefix to external properties, thus `ServerProperties` has
`name="server"` and its configuration properties are `server.port`,
`server.address` etc. In a running Actuator app look at the
"/configprops" endpoint or JMX equivalent.
* Look for use of `RelaxedEnvironment` to pull configuration values
explicitly out of the `Environment`. It often is used with a prefix.
* Look for `@Value` annotations that bind directly to the
`Environment`. This is less flexible than the `RelaxedEnvironment`
approach, but does allow some relaxed binding, specifically for OS
environment variables (so `CAPITALS_AND_UNDERSCORES` are synonyms
for `period.separated`).
* Look for `@ConditionalOnExpression` annotations that switch features
on and off in response to SpEL expressions, normally evaluated with
placeholders resolved from the `Environment`.
## Write a JSON REST Service
Any Spring `@RestController` in a Spring Boot application should
render JSON response by default as long as Jackson2 is on the
classpath. For example:
```java
@RestController
public class MyController {
@RequestMapping("/thing")
public MyThing thing() {
return new MyThing();
}
}
```
As long as `MyThing` can be serialized by Jackson2 (e.g. a normal POJO
or Groovy object) then `http://localhost:8080/thing` will serve a JSON
representation of it by default. Sometimes in a browser you might see
XML responses (but by default only if `MyThing` was a JAXB object)
because browsers tend to send accept headers that prefer XML.
## Customize the Jackson ObjectMapper
Spring MVC (client and server side) uses `HttpMessageConverters` to
negotiate content conversion in an HTTP exchange. If Jackson is on the
classpath you already get a default converter with a vanilla
`ObjectMapper`. Spring Boot has some features to make it easier to
customize this behaviour.
The smallest change that might work is to just add beans of type
`Module` to your context. They will be registered with the default
`ObjectMapper` and then injected into the default message
converter. To replace the default `ObjectMapper` completely, define a
`@Bean` of that type and mark it as `@Primary`.
In addition, if your context contains any beans of type `ObjectMapper`
then all of the `Module` beans will be registered with all of the
mappers. So there is a global mechanism for contributing custom
modules when you add new features to your application.
Finally, if you provide any `@Beans` of type
`MappingJackson2HttpMessageConverter` then they will replace the
default value in the MVC configuration. Also, a convenience bean is
provided of type `HttpMessageConverters` (always available if you use
the default MVC configuration) which has some useful methods to access
the default and user-enhanced message converters.
See also the [section on `HttpMessageConverters`](#message.converters)
and the `WebMvcAutoConfiguration` source code for more details.
<span id="message.converters"/>
## Customize the @ResponseBody Rendering
Spring uses `HttpMessageConverters` to render `@ResponseBody` (or
responses from `@RestControllers`). You can contribute additional
converters by simply adding beans of that type in a Spring Boot
context. If a bean you add is of a type that would have been included
by default anyway (like `MappingJackson2HttpMessageConverter` for JSON
conversions) then it will replace the default value. A convenience
bean is provided of type `HttpMessageConverters` (always available if you
use the default MVC configuration) which has some useful methods to
access the default and user-enhanced message converters (useful, for
example if you want to manually inject them into a custom
`RestTemplate`).
As in normal MVC usage, any `WebMvcConfigurerAdapter` beans that you
provide can also contribute converters by overriding the
`configureMessageConverters` method, but unlike with normal MVC, you
can supply only additional converters that you need (because Spring
Boot uses the same mechanism to contribute its defaults). Finally, if
you opt out of the Spring Boot default MVC configuration by providing
your own `@EnableWebMvc` configuration, then you can take control
completely and do everything manually using `getMessageConverters`
from `WebMvcConfigurationSupport`.
See the `WebMvcAutoConfiguration` source code for more details.
## Add a Servlet, Filter or ServletContextListener to an Application
`Servlet`, `Filter`, `ServletContextListener` and the other listeners
supported by the Servlet spec can be added to your application as
`@Bean` definitions. Be very careful that they don't cause eager
initialization of too many other beans because they have to be
installed in th container very early in the application lifecycle
(e.g. it's not a good idea to have them depend on your `DataSource` or
JPA configuration). You can work around restrictions like that by
initializing them lazily when first used instead of on initialization.
In the case of `Filters` and `Servlets` you can also add mappings and
init parameters by adding a `FilterRegistrationBean` or
`ServletRegistrationBean` instead of or as well as the underlying
component.
## Configure Tomcat
Generally you can follow the advice [here](#discover.options) about
`@ConfigurationProperties` (`ServerProperties` is the main one here),
but also look at `EmbeddedServletContainerCustomizer` and various
Tomcat specific `*Customizers` that you can add in one of those. The
Tomcat APIs are quite rich so once you have access to the
`TomcatEmbeddedServletContainerFactory` you can modify it in a number
of ways. Or the nuclear option is to add your own
`TomcatEmbeddedServletContainerFactory`.
## Use Tomcat 8
Tomcat 8 works with Spring Boot, but the default is to use Tomcat 7
(so we can support Java 1.6 out of the box). You should only need to
change the classpath to use Tomcat 8 for it to work. For example, using
the starter poms in Maven:
```xml
<properties>
<tomcat.version>8.0.3</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
...
```
## Configure Jetty
Generally you can follow the advice [here](#discover.options) about
`@ConfigurationProperties` (`ServerProperties` is the main one here),
but also look at `EmbeddedServletContainerCustomizer`. The Jetty APIs
are quite rich so once you have access to the
`JettyEmbeddedServletContainerFactory` you can modify it in a number
of ways. Or the nuclear option is to add your own
`JettyEmbeddedServletContainerFactory`.
## Use Jetty instead of Tomcat
The Spring Boot starters ("spring-boot-starter-web" in particular) use
Tomcat as an embedded container by default. You need to exclude those
dependencies and include the Jetty ones to use that container. Spring
Boot provides Tomcat and Jetty dependencies bundled together as
separate startes to help make this process as easy as possible.
Example in Maven:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
```
Example in Gradle:
```groovy
configurations {
compile.exclude module: 'spring-boot-starter-tomcat'
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:1.0.0.RC4")
compile("org.springframework.boot:spring-boot-starter-jetty:1.0.0.RC4")
...
}
```
## Use Jetty 9
Jetty 9 works with Spring Boot, but the default is to use Jetty 8 (so
we can support Java 1.6 out of the box). You should only need to
change the classpath to use Jetty 9 for it to work.
If you are using the starter poms and parent you can just add the
Jetty starter and change the version properties, e.g. for a simple
webapp or service:
<properties>
<java.version>1.7</java.version>
<jetty.version>9.1.0.v20131115</jetty.version>
<servlet-api.version>3.1.0</servlet-api.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency
</dependencies>
## Terminate SSL in Tomcat
Add a `EmbeddedServletContainerCustomizer` and in that add a
`TomcatConnectorCustomizer` that sets up the connector to be secure:
```java
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
if(factory instanceof TomcatEmbeddedServletContainerFactory){
TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) factory;
containerFactory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
connector.setPort(serverPort);
connector.setSecure(true);
connector.setScheme("https");
connector.setAttribute("keyAlias", "tomcat");
connector.setAttribute("keystorePass", "password");
try {
connector.setAttribute("keystoreFile", ResourceUtils.getFile("src/ssl/tomcat.keystore").getAbsolutePath());
} catch (FileNotFoundException e) {
throw new IllegalStateException("Cannot load keystore", e);
}
connector.setAttribute("clientAuth", "false");
connector.setAttribute("sslProtocol", "TLS");
connector.setAttribute("SSLEnabled", true);
});
}
}
};
}
```
## Reload Static Content
There are several options. Running in an IDE (especially with
debugging on) is a good way to do development (all modern IDEs allow
reloading of static resources and usually also hotswapping of Java
class changes). The
[Maven](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-tools/spring-boot-maven-plugin#running-applications)
and
[Gradle](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-tools/spring-boot-gradle-plugin#running-a-project-in-place)
tooling also support running from the command line with reloading of
static files. You can use that with an external css/js compiler
process if you are writing that code with higher level tools.
## Reload Thymeleaf Templates Without Restarting the Container
If you are using Thymeleaf, then set
`spring.thymeleaf.cache=false`. See `ThymeleafAutoConfiguration` for
other template customization options.
## Reload Java Classes Without Restarting the Container
Modern IDEs (Eclipse, IDEA etc.) all support hot swapping of bytecode,
so if you make a change that doesn't affect class or method signatures
it should reload cleanly with no side effects.
[Spring Loaded](https://github.com/spring-projects/spring-loaded) goes
a little further in that it can reload class definitions with changes
in the method signatures. With some customization it can force an
`ApplicationContext` to refresh itself (but there is no general
mechanism to ensure that would be safe for a running application
anyway, so it would only ever be a development time trick probably).
<span id="build.hierarchy"/>
## Build an ApplicationContext Hierarchy (Adding a Parent or Root Context)
The
[`SpringApplicationBuilder`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java)
has methods specifically designed for the purpose of building a
hierarchy, e.g.
```java
SpringApplicationBuilder application = new SpringApplicationBuilder();
application.sources(Parent.class).child(Application.class).run(args);
```
There are some restrictions, e.g. the parent aplication context is
*not* a `WebApplicationContext`. Both parent and child are executed
with the same `Environment` constructed in the usual way to include
command line arguments. Any `ServletContextAware` components all have
to go in the child context, otherwise there is no way for Spring Boot
to create the `ServletContext` in time.
## Convert an Existing Application to Spring Boot
For a non-web application it should be easy (throw away the code that
creates your `ApplicationContext` and replace it with calls to
`SpringApplication` or `SpringApplicationBuilder`). Spring MVC web
applications are generally amenable to first creating a deployable WAR
application, and then migrating it later to an executable WAR and/or
JAR. Useful reading is in the
[Getting Started Guide on Converting a JAR to a WAR](http://spring.io/guides/gs/convert-jar-to-war/).
Create a deployable WAR by extending `SpringBootServletInitializer`
(e.g. in a class called `Application`), and add the Spring Boot
`@EnableAutoConfiguration` annotation. Example:
```
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
```
Remember that whatever you put in the "sources" is just a Spring
`ApplicationContext` and normally anything that already works should
work here. There might be some beans you can remove later and let
Spring Boot provide its own defaults for them, but it should be
possible to get something working first.
Static resources can be moved to `/public` (or `/static` or
`/resources` or `/META-INFO/resources`) in the classpath root. Same
for `messages.properties` (Spring Boot detects this automatically in
the root of the classpath).
Vanilla usage of Spring `DispatcherServlet` and Spring Security should
require no further changes. If you have other features in your
application, using other servlets or filters, for instance then you
may need to add some configuration to your `Application` context,
replacing those elements from the `web.xml` as follows:
* A `@Bean` of type `Servlet` or `ServletRegistrationBean` installs
that bean in the container as if it was a `<servlet/>` and
`<servlet-mapping/>` in `web.xml`
* A `@Bean` of type `Filter` or `FilterRegistrationBean` behaves
similarly (like a `<filter/>` and `<filter-mapping/>`.
* An `ApplicationContext` in an XML file can be added to an `@Import`
in your `Application`. Or simple cases where annotation
configuration is heavily used already can be recreated in a few
lines as `@Bean` definitions.
Once the WAR is working we make it executable by adding a `main`
method to our `Application`, e.g.
```java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
```
Applications can fall into more than one category:
* Servlet 3.0 applications with no `web.xml`
* Applications with a `web.xml`
* Applications with a context hierarchy and
* Those without a context hierarchy
All of these should be amenable to translation, but each might require
slightly different tricks.
Servlet 3.0 applications might translate pretty easily if they already
use the Spring Servlet 3.0 initializer support classes. Normally all
the code from an existing `WebApplicationInitializer` can be moved
into a `SpringBootServletInitializer`. If your existing application
has more than one `ApplicationContext` (e.g. if it uses
`AbstractDispatcherServletInitializer`) then you might be able to
squish all your context sources into a single `SpringApplication`. The
main complication you might encounter is if that doesn't work and you
need to maintain the context hierarchy. See the
[entry on building a hierarchy](#build.hierarchy) for examples. An
existing parent context that contains web-specific features will
usually need to be broken up so that all the `ServletContextAware`
components are in the child context.
Applications that are not already Spring applications might be
convertible to a Spring Boot application, and the guidance above might
help, but your mileage may vary.
## Serve Static Content
Spring Boot by default will serve static content from a folder called
`/static` (or `/public` or or `/resources` or `/META-INF/resources`)
in the classpath or from the root of the `ServeltContext`. It uses
the `ResourceHttpRequestHandler` from Spring MVC so you can modify
that behaviour by adding your own `WebMvcConfigurerAdapter` and
overriding the `addResourceHandlers` method.
By default in a standalone web application the default servlet from
the container is also enabled, and acts as a fallback, serving content
from the root of the `ServletContext` if Spring decides not to handle
it. Most of the time this will not happen unless you modify the
deafult MVC configuration because Spring will always be able to handle
requests through the `DispatcherServlet`.
In addition to the 'standard' static resource locations above, a
special case is made for
[Webjars content](http://www.webjars.org/). Any resources with a path
in `/webjars/**` will be served from jar files if they are packaged in
the Webjars format.
For more detail look at the
[`WebMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java?source=c)
source code.
## Switch off the Spring DispatcherServlet
Spring Boot wants to serve all content from the root of your
application "/" down. If you would rather map your own servlet to that
URL you can do it, but of course you may lose some of the other Boot
MVC features. To add your own servlet and map it to the root resource
just declare a `@Bean` of type `Servlet` and give it the special bean
name "dispatcherServlet". (You can also create a bean of a different
type with that name if you want to switch it off and not replace it.)
## Switch off the Default MVC Configuration
The easiest way to take complete control over MVC configuration is to
provide your own `@Configuration` with the `@EnableWebMvc`
annotation. This will leave all MVC configuration in your hands.
## Change the HTTP Port
In a standalone application the main HTTP port defaults to 8080, but
can be set with `server.port` (e.g. in `application.properties` or as
a System property). Thanks to relaxed binding of `Environment` values
you can also use `SERVER_PORT` (e.g. as an OS environment variable).
To switch off the HTTP endpoints completely, but
still create a `WebApplicationContext`, use `server.port=-1` (this is
sometimes useful for testing).
For more detail look at the
[`ServerProperties`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java?source=c)
source code.
## Use a Random Unassigned HTTP Port
To scan for a free port (using OS natives to prevent clashes) use
`server.port=0`.
## Discover the HTTP Port at Runtime
You can access the port the server is running on from log output or
from the `EmbeddedWebApplicationContext` via its
`EmbeddedServletContainer`. The best way to get that and be sure that
it has initialized is to add a `@Bean` of type
`ApplicationListener<EmbeddedServletContainerInitializedEvent>` and
pull the container out of the event wehen it is published.
## Change the HTTP Port or Address of the Actuator Endpoints
In a standalone application the Actuator HTTP port defaults to the
same as the main HTTP port. To make the application listen on a
different port set the external property `management.port`. To listen
on a completely different network address (e.g. if you have an
internal network for management and an external one for user
applications) you can also set `management.address` to a valid IP
address that the server is able to bind to.
For more detail look at the
[`ManagementServerProperties`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/properties/ManagementServerProperties.java?source=c)
source code.
## Customize ViewResolvers
A `ViewResolver` is a core components of Spring MVC, translating view
names in `@Controllers` to actual `View` implementations. Note that
`ViewResolvers` are mainly used in UI applications, rather than
REST-style services (a `View` is not used to render a
`@ResponseBody`). There are many implementations of `ViewResolver` to
choose from, and Spring on its own is not opinionated about which ones
you should use. Spring Boot, on the other hand, installs one or two
for you depending on what it finds on the classpath and in the
application context. The `DispatcherServlet` uses all the resolvers it
finds in the application context, trying each one in turn until it
gets a result, so if you are adding your own you have to be aware of
the order and in which position your resolver is added.
`WebMvcAutoConfiguration` adds the following `ViewResolvers` to your
context:
* An `InternalResourceViewResolver` with bean id
"defaultViewResolver". This one locates physical resources that can be
rendered using the `DefaultServlet` (e.g. static resources and JSP
pages if you are using those). It applies a prefix and a suffix to the
view name and then looks for a physical resource with that path in the
servlet context (defaults are both empty, but accessible for external
configuration via `spring.view.prefix` and `spring.view.suffix`). It
can be overridden by providing a bean of the same type.
* A `BeanNameViewResolver` with id "beanNameViewResolver" is added if
there are beans of type `View`. This is a useful member of the view
resolver chain and will pick up any beans with the same name as the
`View` being resolved. It can be overridden by providing a bean of the
same type, but it's unlikely you will need to do that.
* A `ContentNegotiatingViewResolver` with id
"contentNegotiatingViewResolver" is only added if there are already
beans of type `ViewResolver` present. This is a "master" resolver,
delegating to all the others and attempting to find a match to the
"Accept" HTTP header sent by the client, so it is added with highest
precedence (it is always consulted bythe `DispatcherServlet`). There
is a useful
[blog about `ContentNegotiatingViewResolver`](https://spring.io/blog/2013/06/03/content-negotiation-using-views)
that you might like to study to learn more, and also look at the
source code for detail.
Bear in mind that any custom `ViewResolvers` that you add to your
own application will be consulted by the
`ContentNegotiatingViewResolver`, so make sure they yield `View`
instances that give accurate responses in their `getContentType()`
method.
Also be careful not to define your own `ViewResolver` with id
"contentNegotiatingViewResolver" (like the
`ContentNegotiatingViewResolver`) otherwise, in that case, your bean
will be ovewritten, not the other way round.
* If you use Thymeleaf you will also have a `ThymeleafViewResolver`
with id "thymeleafViewResolver". It looks for resources by surrounding
the view name with a prefix and suffix (externalized to
`spring.thymeleaf.prefix` and `spring.thymeleaf.suffix`, defaults
"classpath:/templates/" and ".html" respectively). It can be
overridden by providing a bean of the same name.
Checkout
[`WebMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java?source=c)
and
[`ThymeleafAutoConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java?source=c)
source code for more detail.
## Customize "Whitelabel" Error Page
The Actuator installs a "whitelabel" error page that you will see in
browser client if you encounter a server error (machine clients
consuming JSON and other media types should see a sensible response
with the right error code). To switch it off you can set
`error.whitelabel.enabled=false`, but normally in addition or
alternatively to that you will want to add your own error page
replacing the whitelabel one. If you are using Thymeleaf you can do
this by adding an "error.html" template. In general what you need is a
`View` that resolves with a name of "error", and/or a `@Controller`
that handles the "/error" path. Unless you replaced some of the
default configuration you should find a `BeanNameViewResolver` in your
`ApplicationContext` so a `@Bean` with id "error" would be a simple
way of doing that. Look at `ErrorMvcAutoConfiguration` for more
options.
## Secure an Application
Web applications will be secure by default (with Basic authentication
on all endpoints) if Spring Security is on the classpath. To add
method-level security to a web application you can simply
`@EnableGlobalMethodSecurity` with your desired settings.
The default `AuthenticationManager` has a single user (username "user"
and password random, printed at INFO when the application starts
up). You can change the password by providing a
`security.user.password`. This and other useful properties are
externalized via `SecurityProperties`.
## Switch off the Spring Boot Security Configuration
If you define a `@Configuration` with `@EnableWebSecurity` anywhere in
your application it will switch off the default webapp security
settings in Spring Boot. To tweak the defaults try setting properties
in `security.*` (see
[SecurityProperties](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java)
for details of available settings).
## Change the AuthenticationManager and add User Accounts
If you provide a `@Bean` of type `AuthenticationManager` the default
one will not be created, so you have the full feature set of Spring
Security available
(e.g. [various authentication options](http://docs.spring.io/spring-security/site/docs/3.2.1.RELEASE/reference/htmlsingle/#jc-authentication)).
Spring Security also provides a convenient
`AuthenticationManagerBuilder` which can be used to build an
`AuthenticationManager` with common options. The recommended way to
use this in a webapp is to inject it into a void method in a
`WebSecurityConfigurerAdapter`, e.g.
```
@Configuration
@Order(0)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
protected void init(AuthenticationManagerBuilder builder) {
builder.inMemoryAuthentication().withUser("barry"); // ... etc.
}
// ... other stuff for application security
}
```
The configuration class that does this should declare an `@Order` so
that it is used before the default one in Spring Boot (which has very
low precedence).
## Use 'Short' Command Line Arguments
Some people like to use (for example) `--port=9000` instead of
`--server.port=9000` to set configuration properties on the command
line. You can easily enable this by using placeholders in
`application.properties`, e.g.
```properties
server.port: ${port:8080}
```
> Note that in this specific case the port binding will work in a PaaS
> environment like Heroku and Cloud Foundry, since in those two
> platforms the `PORT` environment variable is set automatically and
> Spring can bind to capitalized synonyms for `Environment`
> properties.
## Configure Logback for Logging
Spring Boot has no mandatory logging dependence, except for the
`commons-logging` API, of which there are many implementations to
choose from. To use [Logback](http://logback.qos.ch) you need to
include it, and some bindings for `commons-logging` on the classpath.
The simplest way to do that is through the starter poms which all
depend on `spring-boot-start-logging`. For a web application you only
need the web starter since it depends transitively on the logging
starter. E.g. in Maven:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
Spring Boot has a `LoggingSystem` abstraction that attempts to select
a system depending on the contents of the classpath. If Logback is
available it is the first choice. So if you put a `logback.xml` in the
root of your classpath it will be picked up from there. Spring Boot
provides a default base configuration that you can include if you just
want to set levels, e.g.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="DEBUG"/>
</configuration>
```
If you look at the default `logback.xml` in the spring-boot JAR you
will see that it uses some useful System properties which the
`LoggingSystem` takes care of creating for you. These are:
* `${PID}` the current process ID
* `${LOG_FILE}` if `logging.file` was set in Boot's external configuration
* `${LOG_PATH` if `logging.path` was set (representing a directory for
log files to live in)
Spring Boot also provides some nice ANSI colour terminal output on a
console (but not in a log file) using a custom Logback converter. See
the default `base.xml` configuration for details.
If Groovy is on the classpath you should be able to configure Logback
with `logback.groovy` as well (it will be given preference if
present).
## Configure Log4j for Logging
Spring Boot supports [Log4j](http://logging.apache.org/log4j/1.x/) for
logging configuration, but it has to be on the classpath. If you are
using the starter poms for assembling dependencies that means you have
to exclude logback and then include log4j back. If you aren't using
the starter poms then you need to provide `commons-logging` (at least)
in addition to Log4j.
The simplest path to using Log4j is probably through the starter poms,
even though it requires some jiggling with excludes, e.g. in Maven:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>${project.groupId}</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
```
Note the use of the log4j starter to gather together the dependencies
for common logging requirements (e.g. including having Tomcat use
`java.util.logging` but configure the output using Log4j). See the
[Actuator Log4j Sample]() for more detail and to see it in action.
## Test a Spring Boot Application
A Spring Boot application is just a Spring `ApplicationContext` so
nothing very special has to be done to test it beyond what you would
normally do with a vanilla Spring context. One thing to watch out for
though is that the external properties, logging and other features of
Spring Boot are only installed in the context by default if you use
`SpringApplication` to create it. Spring Boot has a special Spring
`@ContextConfiguration` annotation, so you can use this for example
(from the JPA Sample):
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)
public class CityRepositoryIntegrationTests {
@Autowired
CityRepository repository;
...
```
To use the `@SpringApplicationConfiguration` you need the test jar on
your classpath (recommended Maven co-ordinates
"org.springframework.boot:spring-boot-starter-test"). The context
loader guesses whether you want to test a web application or not
(e.g. with `MockMVC`) by looking for the `@WebAppConfiguration`
annotation. (`MockMVC` and `@WebAppConfiguration` are from the Spring
Test support library).
<span id="main.properties"/>
## Externalize the Configuration of SpringApplication
A `SpringApplication` has bean properties (mainly setters) so you can
use its Java API as you create the application to modify its
behaviour. Or you can externalize the configuration using properties
in `spring.main.*`. E.g. in `application.properties` you might have
```properties
spring.main.web_environment: false
spring.main.show_banner: false
```
and then the Spring Boot banner will not be printed on startup, and
the application will not be a web application.
## Create a Non-Web Application
Not all Spring applications have to be web applications (or web
services). If you want to execute some code in a `main` method, but
also bootstrap a Spring application to set up the infrastructure to
use, then it's easy with the `SpringApplication` features of Spring
Boot. A `SpringApplication` changes its `ApplicationContext` class
depending on whether it thinks it needs a web application or not. The
first thing you can do to help it is to just leave the servlet API
dependencies off the classpath. If you can't do that (e.g. you are
running 2 applications from the same code base) then you can
explicitly call `SpringApplication.setWebEnvironment(false)`, or set
the `applicationContextClass` property (through the Java API or with
[external properties](#main.properties)). Application code that you
want to run as your business logic can be implemented as a
`CommandLineRunner` and dropped into the context as a `@Bean`
definition.
## Create a Deployable WAR File
Use the `SpringBootServletInitializer` base class, which is picked up
by Spring's Servlet 3.0 support on deployment. Add an extension of
that to your project and build a WAR file as normal. For more detail,
see the ["Converting a JAR Project to a WAR" guide][gs-war] on the
spring.io website.
The WAR file can also be executable if you use the Spring Boot build
tools. In that case the embedded container classes (to launch Tomcat
for instance) have to be added to the WAR in a `lib-provided`
directory. The tools will take care of that as long as the
dependencies are marked as "provided" in Maven or Gradle. Here's a
Maven example
[in the Boot Samples](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-samples/spring-boot-sample-traditional/pom.xml).
A Spring Boot application deployed as a WAR file has most of the same
features as one executed from an archive, or from source code. For
example, `@Beans` of type `Servlet` and `Filter` will be detected and
mapped on startup. An exception is error page declarations, which is
essentially a consequence of the fact that there is no Java API in the
Servlet spec for adding error pages. You have to add a `web.xml` with
a global error page mapped to "/error" for the deployed WAR to work
the same way if it has error page mappings (all Actuator apps have an
error page by default). Example:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<error-page>
<location>/error</location>
</error-page>
</web-app>
```
[gs-war]: http://spring.io/guides/gs/convert-jar-to-war
## Create a Deployable WAR File for older Servlet Containers
Older Servlet containers don't have support for the
`ServletContextInitializer` bootstrap process used in Servlet 3.0. You
can still use Spring and Spring Boot in these containers but you are
going to need to add a `web.xml` to your application and configure it
to load an `ApplicationContext` via a `DispatcherServlet`.
TODO: add some detail.
## Configure a DataSource
Spring Boot will create a `DataSource` for you if you have
`spring-jdbc` and some other things on the classpath. Here's the
algorithm for choosing a specific implementation.
* We prefer the Tomcat pooling `DataSource` for its performance and
concurrency, so if that is available we always choose it.
* If commons-dbcp is available we will use that, but we don't
recommend it in production.
* If neither of those is available but an embedded database is then we
create one of those for you (preference order is h2, then Apache
Derby, then hsqldb).
The pooling `DataSource` option is controlled by external
configuration properties in `spring.datasource.*` for example:
```properties
spring.datasource.url: jdbc:mysql://localhost/test
spring.datasource.username: root
spring.datasource.password:
spring.datasource.driverClassName: com.mysql.jdbc.Driver
```
The `@ConfigurationProperties` for `spring.datasource` are defined in
`AbstractDataSourceConfiguration` (so see there for more options).
For a pooling `DataSource` to be created we need to be able to verify
that a valid `Driver` class is available, so we check for that before
doing anything. I.e. if you set
`spring.datasource.driverClassName=com.mysql.jdbc.Driver` then that
class has to be loadable.
To override the default settings just define a `@Bean` of your own of
type `DataSource`. See
[`DataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java)
for more details.
## Use Spring Data Repositories
Spring Data can create implementations for you of `@Repository`
interfaces of various flavours. Spring Boot will handle all of that
for you as long as those `@Repositories` are included in the same
package (or a sub-package) of your `@EnableAutoConfiguration` class.
For many applications all you will need is to put the right Spring
Data dependencies on your classpath (there is a
"spring-boot-starter-data-jpa" for JPA and for Mongodb you only need
to add "spring-datamongodb"), create some repository interfaces to
handle your `@Entity` objects. Examples are in the
[JPA sample](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-jpa)
or the
[Mongodb sample](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-mongodb).
Spring Boot tries to guess the location of your `@Repository`
definitions, based on the `@EnableAutoConfiguration` it finds. To get
more control, use the `@EnableJpaRepositories` annotation (from Spring
Data JPA).
## Separate @Entity Definitions from Spring Configuration
Spring Boot tries to guess the location of your `@Entity` definitions,
based on the `@EnableAutoConfiguration` it finds. To get more control,
you can use the `@EntityScan` annotation, e.g.
```java
@Configuration
@EnableAutoConfiguration
@EntityScan(basePackageClasses=City.class)
public class Application {
...
}
```
## Configure JPA Properties
Spring JPA already provides some vendor-independent configuration
options (e.g. for SQL logging) and Spring Boot exposes those, and a
few more for hibernate as external configuration properties. The most
common options to set are
```properties
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database: H2
spring.jpa.show-sql: true
```
(Because of relaxed data binding hyphens or underscores should work
equally well as property keys.) The `ddl-auto` setting is a special
case in that it has different defaults depending on whether you are
using an embedded database ("create-drop") or not ("none"). In
addition all properties in `spring.jpa.properties.*` are passed
through as normal JPA properties (with the prefix stripped) when the
local `EntityManagerFactory` is created.
See
[`HibernateJpaAutoConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)
and
[`JpaBaseConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)
for more details.
## Use a Traditional persistence.xml
Spring doesn't require the use of XML to configure the JPA provider,
and Spring Boot assumes you want to take advantage of that feature. If
you prefer to use `persistence.xml` then you need to define your own
`@Bean` of type `LocalEntityManagerFactoryBean`, and set the
persistence unit name there.
See
[`JpaBaseConfiguration`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)
for the default settings.
## Initialize a Database
An SQL database can be initialized in different ways depending on what
your stack is. Or of course you can do it manually as long as the
database is in a server.
### JPA
JPA has features for DDL generation, and these can be set up to
run on startup against the database. This is controlled through two
external properties:
* `spring.jpa.generate-ddl` (boolean) switches the feature on and off
and is vendor independent
* `spring.jpa.hibernate.ddl-auto` (enum) is a Hibernate feature that
controls the behaviour in a more fine-grained way. See below for
more detail.
### Hibernate
You can set `spring.jpa.hibernate.ddl-auto` explicitly and the
standard Hibernate property values are "none", "validate", "update",
"create-drop". Spring Boot chooses a default value for you based on
whether it thinks your database is embedded (default "create-drop") or
not (default "none"). An embedded database is detected by looking at
the `Connection` type: `hsqldb`, `h2` and `derby` are embedded, the
rest are not. Be careful when switching from in-memory to a "real"
database that you don't make assumptions about the existence of the
tables and data in the new platform. You either have to set "ddl-auto"
expicitly, or use one of the other mechanisms to initialize the
database.
In addition, a file named "import.sql" in the root of the classpath
will be executed on startup. This can be useful for demos and for
testing if you are carefuil, but probably not something you want to be
on the classpath in production. It is a Hibernate feature (nothing to
do with Spring).
### Spring JDBC
Spring JDBC has a `DataSource` initializer feature. Spring Boot
enables it by default and loads SQL from the standard locations
`schema.sql` and `data.sql` (in the root of the classpath). In
addition Spring Boot will load a file `schema-${platform}.sql` where
`platform` is the vendor name of the database (`hsqldb`, `h2,
`oracle`, `mysql`, `postgresql` etc.). Spring Boot enables the
failfast feature of the Spring JDBC initializer by default, so if
the scripts cause exceptions the application will fail.
To disable the failfast you can set
`spring.datasource.continueOnError=true`. This can be useful once an
application has matured and been deployed a few times, since the
scripts can act as "poor man's migrations" - inserts that fail mean
that the data is already there, so there would be no need to prevent
the application from running, for instance.
### Spring Batch
If you are using Spring Batch then it comes pre-packaged with SQL
initialization scripts for most popular database platforms. Spring
Boot will detect your database type, and execute those scripts by
default, and in this case will switch the fail fast setting to false
(errors are logged but do not prevent the application from
starting). This is because the scripts are known to be reliable and
generally do not contain bugs, so errors are ignorable, and ignoring
them makes the scripts idempotent. You can switch off the
initialization explicitly using
`spring.batch.initializer.enabled=false`.
### Higher Level Migration Tools
Spring Boot works fine with higher level migration tools
[Flyway](http://flywaydb.org/) (SQL-based) and
[Liquibase](http://www.liquibase.org/) (XML). In general we prefer
Flyway because it is easier on the eyes, and it isn't very common to
need platform independence: usually only one or at most couple of
platforms is needed.
## Execute Spring Batch Jobs on Startup
Spring Batch autoconfiguration is enabled by adding
`@EnableBatchProcessing` (from Spring Batch) somewhere in your
context.
By default it executes *all* `Jobs` in the application context on
startup (see
[JobLauncherCommandLineRunner](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java)
for details). You can narrow down to a specific job or jobs by
specifying `spring.batch.job.names` (comma separated job name
patterns).
If the application context includes a `JobRegistry` then
the jobs in `spring.batch.job.names` are looked up in the regsitry
instead of bein autowired from the context. This is a common pattern
with more complex systems where multiple jobs are defined in child
contexts and registered centrally.
See
[BatchAutoConfiguration](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java)
and
[@EnableBatchProcessing](https://github.com/spring-projects/spring-batch/blob/master/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.java)
for more details.
<span id="discover.options"/>
## Discover Built-in Options for External Properties
Spring Boot binds external properties from `application.properties`
(or `.yml`) (and other places) into an application at runtime. There
is not (and technically cannot be) an exhaustive list of all supported
properties in a single location because contributions can come from
additional JAR files on your classpath.
A running application with the Actuator features has a "/configprops"
endpoint that shows all the bound and bindable properties available
through `@ConfigurationProperties` (also exposed through JMX if you
don't have a web endpoint).
There is a sample
[`application.yml`](https://github.com/spring-projects/spring-boot/blob/master/docs/application.yml)
with a non-exhaustive and possibly inaccurate list of properties
supported by Spring Boot vanilla with autoconfiguration. The
definitive list comes from searching the source code for
`@ConfigurationProperties` and `@Value` annotations, as well as the
occasional use of `RelaxedEnvironment`
(c.f. [here](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java?source=c#L65)).
## Set the Active Spring Profiles
The Spring `Environment` has an API for this, but normally you would
set a System profile (`spring.profiles.active`) or an OS environment
variable (`SPRING_PROFILES_ACTIVE`). E.g. launch your application with
a `-D...` argument (remember to put it before the main class or jar
archive):
```
java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
```
In Spring Boot you can also set the active profile in
`application.properties`, e.g.
```properties
spring.profiles.active=production
```
A value set this way is replaced by the System property or environment
variable setting, but not by the `SpringApplicationBuilder.profiles()`
method. Thus the latter Java API can be used to augment the profiles
without changing the defaults.
## Change the Location of External Properties of an Application
By default properties from different sources are added to the Spring
`Environment` in a defined order, and the precedence for resolution is
1) commandline, 2) filesystem (current working directory)
`application.properties`, 3) classpath `application.properties`.
A nice way to augment and modify this is to add `@PropertySource`
annotations to your application sources. Classes passed to the
`SpringApplication` static convenience methods, and those added using
`setSources()` are inspected to see if they have `@PropertySources`
and if they do those properties are added to the `Environment` early
enough to be used in all phases of the `ApplicationContext`
lifecycle. Properties added in this way have precendence over any
added using the default locations, but have lower priority than system
properties, environment variables or the command line.
You can also provide System properties (or environment variables) to
change the behaviour:
* `spring.config.name` (`SPRING_CONFIG_NAME`), defaults to
`application` as the root of the file name
* `spring.config.location` (`SPRING_CONFIG_LOCATION`) is file to load
(e.g. a classpath resource or a URL). A separate `Environment`
property source is set up for this document and it can be overridden
by system properties, environment variables or the command line.
No matter what you set in the environment, Spring Boot will always
load `application.properties` as described above. If YAML is used then
files with the ".yml" extension are also added to the list by default.
See `ConfigFileApplicationListener` for more detail.
## Use YAML for External Properties
YAML is a superset of JSON and as such is a very convenient syntax for
storing external properties in a hierarchical format. E.g.
```yaml
spring:
application:
name: cruncher
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/test
server:
port: 9000
```
Create a file called `application.yml` and stick it in the root of
your classpath, and also add `snakeyaml` to your classpath (Maven
co-ordinates `org.yaml:snakeyaml`, already included if you use a
Spring Boot Starter). A YAML file is parsed to a Java
`Map<String,Object>` (like a JSON object), and Spring Boot flattens
the maps so that it is 1-level deep and has period-separated keys, a
lot like people are used to with `Properties` files in Java.
The example YAML above corresponds to an `application.properties` file
```properties
spring.application.name: cruncher
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.datasource.url: jdbc:mysql://localhost/test
server.port: 9000
```
## Change Configuration Depending on the Environment
A YAML file is actually a sequence of documents separated by `---`
lines, and each document is parsed separately to a flattened map.
If a YAML document contains a `spring.profiles` key, then the
profiles value (comma-separated list of profiles) is fed into the
Spring `Environment.acceptsProfiles()` and if any of those profiles is
active that document is included in the final merge (otherwise not).
Example:
```yaml
server:
port: 9000
---
spring:
profiles: development
server:
port: 9001
---
spring:
profiles: production
server:
port: 0
```
In this example the default port is 9000, but if the Spring profile
"development" is active then the port is 9001, and if "production" is
active then it is 0.
The YAML documents are merged in the order they are encountered (so
later values override earlier ones).
To do the same thing with properties files you can use
`application-${profile}.properties` to specify profile-specific
values.
## Customize the Environment or ApplicationContext Before it Starts
A `SpringApplication` has `ApplicationListeners` and
`ApplicationContextInitializers` that are used to apply customizations
to the context or environment. Spring Boot loads a number of such
customizations for use internally from
`META-INF/spring.factories`. There is more than one way to register
additional ones:
* programmatically per application by calling the `addListeners` and
`addInitializers` methods on `SpringApplication` before you run it
* declaratively per application by setting
`context.initializer.classes` or `context.listener.classes`
* declarative for all applications by adding a
`META-INF/spring.factories` and packaging a jar file that the
applications all use as a library
The `SpringApplication` sends some special `ApplicationEvents` to the
listeners (even some before the context is created), and then registers
the listeners for events published by the `ApplicationContext` as well:
* `ApplicationStartedEvent` at the start of a run, but before any
processing except the registration of listeners and initializers.
* `ApplicationEnvironmentPreparedEvent` when the `Environment`
to be used in the context is known, but before the context is
created.
* `ApplicationPreparedEvent` just before the refresh is
started, but after bean definitions have been loaded.
* `ApplicationFailedEvent` if there is an exception on startup.
## Build An Executable Archive with Ant
To build with Ant you need to grab dependencies and compile and then
create a JAR or WAR archive as normal. To make it executable:
1. Use the appropriate launcher as a `Main-Class`,
e.g. `org.springframework.boot.loader.JarLauncher` for a JAR file, and
specify the other stuff it needs as manifest entries, principally a
`Start-Class`.
2. Add the runtime dependencies in a nested "lib" directory (for a
JAR) and the "provided" (embedded container) dependencies in a nested
"lib-provided" directory. Remember *not* to compress the entries in
the archive.
3. Add the `spring-boot-loader` classes at the root of the archive (so
the `Main-Class` is available).
Example
<target name="build" depends="compile">
<copy todir="target/classes/lib">
<fileset dir="lib/runtime" />
</copy>
<jar destfile="target/spring-boot-sample-actuator-${spring-boot.version}.jar" compress="false">
<fileset dir="target/classes" />
<fileset dir="src/main/resources" />
<zipfileset src="lib/loader/spring-boot-loader-jar-${spring-boot.version}.jar" />
<manifest>
<attribute name="Main-Class" value="org.springframework.boot.loader.JarLauncher" />
<attribute name="Start-Class" value="${start-class}" />
</manifest>
</jar>
</target>
The [Actuator Sample]() has a `build.xml` that should work if you run
it with
$ ant -lib <path_to>/ivy-2.2.jar
after which you can run the application with
$ java -jar target/*.jar
The How-to guide has moved and is now published as part of the reference documentation.
You can find the latest browsable copy at
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto
If you want to contribute to the How-to the source is available at
[`spring-boot-docs/src/main/asciidoc/howto.adoc`](../spring-boot-docs/src/main/asciidoc/howto.adoc).

View File

@ -1,376 +0,0 @@
# Spring Boot - Actuator
> **Note:** Some of this documentation covers concepts from other modules, it will be
> cleaned up before the final release.
The aim of this project is minimum fuss for getting applications up
and running in production, and in other environments. There is a
strong emphasis on implementing RESTful web services but many features
are more generic than that.
|Feature |Implementation |Notes |
|---|---|---|
|Server |Tomcat or Jetty | Whatever is on the classpath |
|REST |Spring MVC | |
|Security |Spring Security | If on the classpath |
|Logging |Logback, Log4j or JDK | Whatever is on the classpath. Sensible defaults. |
|Database |HSQLDB or H2 | Per classpath, or define a DataSource to override |
|Externalized configuration | Properties or YAML | Support for Spring profiles. Bind automatically to @Bean. |
|Audit | Spring Security and Spring ApplicationEvent |Flexible abstraction with sensible defaults for security events |
|Validation | JSR-303 |If on the classpath |
|Management endpoints | Spring MVC | Health, basic metrics, request tracing, shutdown, thread dumps |
|Error pages | Spring MVC | Sensible defaults based on exception and status code |
|JSON |Jackson 2 | |
|ORM |Spring Data JPA | If on the classpath |
|Batch |Spring Batch | If enabled and on the classpath |
|Integration Patterns |Spring Integration | If on the classpath |
For a quick introduction and to get started quickly with a new
project, carry on reading. For more in depth coverage of the features
of Spring Boot Actuator, go to the
[Feature Guide](docs/Features.md).
# Getting Started
You will need Java (6 at least) and a build tool (Maven is what we use
below, but you are more than welcome to use gradle). These can be
downloaded or installed easily in most operating systems. For Ubuntu:
$ sudo apt-get install openjdk-6-jdk maven
<!--FIXME: short instructions for Mac.-->
## A basic project
If you are using Maven create a really simple `pom.xml` with 2 dependencies:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myproject</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{{project.version}}</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
If you like Gradle, that's fine, and you will know what to do with
those dependencies. The first dependency adds Spring Boot auto
configuration and the Tomcat container to your application, and the
second one adds some more opinionated stuff like the default
management endpoints. If you prefer Jetty you can just add the
embedded Jetty jars to your classpath instead of Tomcat (once you
exclude the `spring-starter-tomcat` dependency).
## Adding a business endpoint
To do something useful to your business you need to add at least one
endpoint. An endpoint can be implemented as a Spring MVC
`@Controller`, e.g.
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
public Map<String, String> helloWorld() {
return Collections.singletonMap("message", "Hello World");
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
You can use the main method to launch it from your project jar. You
can also launch that straight using the Spring Boot CLI (without
the `@EnableAutoConfiguration` and even without the import statements
that your IDE will add if you are using one), if you just add
```
@Grab("org.springframework.boot:spring-boot-starter-actuator:{{project.version}}")
```
and package and run:
$ mvn package
$ java -jar target/myproject-1.0.0-SNAPSHOT.jar
$ curl localhost:8080/
{"message": "Hello World"}
There are also some endpoins that you didn't implement by came free
with the Actuator:
$ curl localhost:8080/health
ok
$ curl localhost:8080/metrics
{"counter.status.200.health":1.0,"gauge.response.health":10.0,"mem":120768.0,"mem.free":105012.0,"processors":4.0}
`/health` is the default location for the health endpoint - it tells
you if the application is running and healthy. `/metrics` is the default
location for the metrics endpoint - it gives you basic counts and
response timing data by default but there are plenty of ways to
customize it. You can also try `/trace` and `/dump` to get some
interesting information about how and what your app is doing.
## Running the application
You can package the app and run it as a jar (as above) and that's very
convenient for production usage. Or there are other options, many of
which are more convenient at development time. Here are a few:
1. Use the Maven exec plugin, e.g.
$ mvn exec:java
2. Run directly in your IDE, e.g. Eclipse or IDEA let you right click
on a class and run it.
3. Use a different Maven plugin.
4. Find feature in Gradle that does the same thing.
5. Use the Spring executable. <!--FIXME: document this maybe.-->
## Externalizing configuration
Spring Boot likes you to externalize your configuration so you
can work with the same application code in different environments. To
get started with this you create a file in the root of your classpath
(`src/main/resources` if using Maven) - if you like YAML, you can include
`org.yaml:snakeyaml` on your runtime class path, and call the file `application.yml`,
e.g.:
server:
port: 9000
management:
port: 9001
logging:
file: target/log.out
or if you like Java `Properties` files, you can call it
`application.properties`, e.g.:
server.port: 9000
management.port: 9001
logging.file: target/log.out
Those examples are properties that Spring Boot itself binds to
out of the box, so if you make that change and run the app again, you
will find the home page on port 9000 instead of 8080:
$ curl localhost:9000/
{"message": "Hello World"}
and the management endpoints on port 9001 instead of 8080:
$ curl localhost:9001/health
ok
To externalize business configuration you can simply add a default
value to your configuration file, e.g.
server:
port: 9000
management:
port: 9001
logging:
file: target/log.out
service:
message: Awesome Message
and then bind to it in the application code. The simplest way to do
that is to simply refer to it in an `@Value` annotation, e.g.
@Controller
@EnableAutoConfiguration
public class SampleController {
@Value("${service.message:Hello World}")
private String value = "Goodbye Everyone"
@RequestMapping("/")
@ResponseBody
public Map<String, String> helloWorld() {
return Collections.singletonMap("message", message);
}
...
}
That's a little bit confusing because we have provided a message value
in three different places - in the external configuration ("Awesome
Message"), in the `@Value` annotation after the colon ("Hello World"),
and in the filed initializer ("Goodbye Everyone"). That was only to
show you how and you only need it once, so it's your choice (it's
useful for unit testing to have the Java initializer as well as the
external value). Note that the YAML object is flattened using period
separators.
For simple Strings where you have sensible defaults `@Value` is
perfect, but if you want more and you like everything strongly typed
then you can have Spring bind the properties and validate them
automatically in a separate value object. For instance:
// ServiceProperties.java
@ConfigurationProperties(name="service")
public class ServiceProperties {
private String message;
private int value = 0;
... getters and setters
}
// SampleController.java
@Controller
@EnableAutoConfiguration
@EnableConfigurationProperties(ServiceProperties.class)
public class SampleController {
@Autowired
private ServiceProperties properties;
@RequestMapping("/")
@ResponseBody
public Map<String, String> helloWorld() {
return Collections.singletonMap("message", properties.getMessage());
}
...
}
When you ask to
`@EnableConfigurationProperties(ServiceProperties.class)` you are
saying you want a bean of type `ServiceProperties` and that you want
to bind it to the Spring Environment. The Spring Environment is a
collection of name-value pairs taken from (in order of decreasing
precedence) 1) the command line, 2) the external configuration file,
3) System properties, 4) the OS environment. Validation is done based
on JSR-303 annotations by default provided that library (and an
implementation) is on the classpath.
## Adding security
If you add Spring Security java config to your runtime classpath you
will enable HTTP basic authentication by default on all the endpoints.
In the `pom.xml` it would look like this:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Try it out:
$ curl localhost:8080/
{"status": 403, "error": "Forbidden", "message": "Access Denied"}
$ curl user:<password>@localhost:8080/
{"message": "Hello World"}
The default auto configuration has an in-memory user database with one
entry, and the `<password>` value has to be read from the logs (at
INFO level) by default. If you want to extend or expand that, or
point to a database or directory server, you can add the `@EnableGlobalAuthentication`
annotation and configure the global `AuthenticationManagerBuilder` as shown below:
@Controller
@EnableAutoConfiguration
@EnableGlobalAuthentication
public class SampleController {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("client").password("secret").roles("USER");
}
...
}
Try it out:
$ curl user:password@localhost:8080/
{"status": 403, "error": "Forbidden", "message": "Access Denied"}
$ curl client:secret@localhost:8080/
{"message": "Hello World"}
## Adding a database
Just add `spring-jdbc` and an embedded database to your dependencies:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
Then you will be able to inject a `DataSource` into your controller:
@Controller
@EnableAutoConfiguration
@EnableConfigurationProperties(ServiceProperties.class)
public class SampleController {
private JdbcTemplate jdbcTemplate;
@Autowired
public SampleController(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@RequestMapping("/")
@ResponseBody
public Map<String, String> helloWorld() {
return jdbcTemplate.queryForMap("SELECT * FROM MESSAGES WHERE ID=?", 0);
}
...
}
The app will run (with the new security configuration):
$ curl client:secret@localhost:8080/
{"error":"Internal Server Error", "status":500, "exception":...}
but there's no data in the database yet and the `MESSAGES` table
doesn't even exist, so there's an error. One easy way to fix it is
to provide a `schema.sql` script in the root of the classpath, e.g.
create table MESSAGES (
ID BIGINT NOT NULL PRIMARY KEY,
MESSAGE VARCHAR(255)
);
INSERT INTO MESSAGES (ID, MESSAGE) VALUES (0, 'Hello Phil');
Now when you run the app you get a sensible response:
$ curl client:secret@localhost:8080/
{"ID":0, "MESSAGE":"Hello Phil"}
Obviously, this is only the start, but hopefully you have a good grasp
of the basics and are ready to try it out yourself.

View File

@ -1,156 +0,0 @@
# Spring Actuator Feature Guide
Here are some (most, hopefully all) the features of Spring Actuator
with some commentary to help you start using them. We
recommend you first build a project with the Actuator (e.g. the
getting started project from the main README), and then try each
feature in turn there.
Many useful features of
[Spring Boot](../../spring-boot/README.md) are all available
in an Actuator application.
TODO: group things together and break them out into separate files.
## Customizing Management Endpoints
The `ManagementProperties` are bound to application properties, and
can be used to specify
* The port that the application listens on for the management
endpoints (defaults to 8080)
* The address that the management endpoints are available on (if the
port is different to the main server port). Use this to listen only
on an internal or ops-facing network, for instance, or to only
listen for connections from localhost (by specifying "127.0.0.1")
* The context root of the management endpoints
## Error Handling
The Actuator provides an `/error` mapping by default that handles all
errors in a sensible way. If you want more specific error pages for
some conditions, the embedded servlet containers support a uniform
Java DSL for customizing the error handling. To do this you have to
have picked a container implementation (by including either Tomcat or
Jetty on the classpath), but then the API is the same. TODO: finish
this.
## Info Endpoint
By default the Actuator adds an `/info` endpoint to the main server.
It contains the commit and timestamp information from `git.properties`
(if that file exists) and also any properties it finds in the
environment with prefix "info".
To populate `git.properties` in a
Maven build you can use the excellent
[git-commit-id-plugin](https://github.com/ktoso/maven-git-commit-id-plugin).
To populate the "info" map all you need to do is add some stuff to
`application.properties`, e.g.
info.app.name: MyService
info.app.description: My awesome service
info.app.version: 1.0.0
If you are using Maven you can automcatically populate info properties
from the project using resource filtering. In your `pom.xml` you
have (inside the `<build/>` element):
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
and then in the `application.properties` you can refer to project
properties via placeholders, e.g.
project.artifactId: myproject
project.name: Demo
project.version: X.X.X.X
project.description: Demo project for info endpoint
info.build.artifact: ${project.artifactId}
info.build.name: ${project.name}
info.build.description: ${project.description}
info.build.version: ${project.version}
(notice that in the example we used `project.*` to set some values to
be used as fallbacks if the Maven resource filtering has for some
reason not been switched on).
## Security - Basic Authentication
To secure your endpoints just add Spring Security Javaconfig to the
classpath. By default HTTP Basic authentication will be applied to
every request in the main server (and the management server if it is
running on the same port). There is a single account by default, and
you can test it like this:
$ curl user:password@localhost:8080/metrics
... stuff comes out
If the management server is running on a different port it is
unsecured by default. If you want to secure it you can add a security
auto configuration explicitly
## Security - HTTPS
Ensuring that all your main endpoints are only available over HTTPS is
an important chore for any application. If you are using Tomcat as a
servlet container, then the Actuator will add Tomcat's own
`RemoteIpValve` automatically if it detects some environment settings,
and you should be able to rely on the `HttpServletRequest` to report
whether or not it is secure (even downstream of the real SSL
termination endpoint). The standard behaviour is determined by the
presence or absence of certain request headers ("x-forwarded-for" and
"x-forwarded-proto"), whose names are conventional, so it should work
with most front end proxies. You switch on the valve by adding some
entries to `application.properties`, e.g.
server.tomcat.remote_ip_header: x-forwarded-for
server.tomcat.protocol_header: x-forwarded-proto
(The presence of either of those properties will switch on the
valve. Or you can add the `RemoteIpValve` yourself by adding a
`TomcatEmbeddedServletContainerFactory` bean.)
Spring Security can also be configured to require a secure channel for
all (or some requests). To switch that on in an Actuator application
you just need to set `security.require_https: true` in
`application.properties`.
## Audit Events
The Actuator has a flexible audit framework that will publish events
once Spring Security is in play (authentication success and failure
and access denied exceptions by default). This can be very useful for
reporting, and also to implement a lock-out policy based on
authentication failures.
You can also choose to use the audit services for your own business
events. To do that you can either inject the existing
`AuditEventRepository` into your own components and use that directly,
or you can simply publish `AuditApplicationEvent` via the Spring
`ApplicationContext` (using `ApplicationEventPublisherAware`).
## Metrics Customization
Metrics come out on the `/metrics` endpoint. You can add additional
metrics by injecting a `MetricsRepository` into your application
components and adding metrics whenever you need to. To customize the
`MetricsRepository` itself, just add a bean definition of that type to
the application context (only in memory is supported out of the box
for now).
## Customizing the Health Indicator
The application always tells you if it's healthy via the `/health`
endpoint. By default it just responds to a GET witha 200 status and a
plain text body containing "ok". If you want to add more detailed
information (e.g. a description of the current state of the
application), just add a bean of type `HealthIndicator` to your
application context, and it will take the place of the default one.

View File

@ -1,123 +0,0 @@
# Spring Boot - AutoConfigure
Spring Boot AutoConfiguration attempts to automatically configure your Spring application
based on the dependencies that it declares. 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.
##Enabling auto-configuration
Add an `@EnableAutoConfiguration` annotation to your primary `@Configuration` class to
enable auto-configuration:
```java
import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration
public class MyConfiguration {
}
```
Currently auto-configuration is provided for the following types of application:
* Web (Tomcat or Jetty, Spring MVC)
* JDBC (Commons DBCP, embedded databases, jdbcTemplate)
* JPA with Hibernate
* Spring Data JPA (automatically detecting `Repository` classes)
* Spring Batch (including `JobLauncherCommandLineRunner`s and database initialization)
* Thymeleaf templating
* Reactor asynchronous JVM programming
###Understanding auto-configured beans
Under the hood, auto-configuration is implemented with standard `@Configuration` classes.
Additional `@Conditional` annotations are used to constrain when the auto-configuration
should apply. Usually auto-configuration classes use `@ConditionalOnClass` and
`@ConditionalOnMissingBean` annotations. This ensures that auto-configuration only
applies when relevant classes are found and when you have not declared your own
`@Configuration`.
You can browse the source code of `spring-boot-autoconfigure` to see the `@Configuration`
classes that we provide (see the `META-INF/spring.factories` file).
> **Note:** If you are using `org.springframework.boot.SpringApplication`, you can see
> which `@Conditions` were not applied by starting your application with the `--debug`
> option.
###Disabling specific auto-configuration
All auto-configuration that we provide attempts to back away as you start to define your
own beans. If, however, 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.
```java
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={EmbeddedDatabaseConfiguration.class})
public class MyConfiguration {
}
```
##Condition annotations
Spring Boot Auto-Configure includes a number of `@Conditional` annotations that are used
limit when auto-configure is applied. You can reuse these in your own code by annotating
`@Configuration` classes or individual `@Bean` methods.
###Class conditions
The `ConditionalOnClass` and `ConditionalOnMissingClass` annotations allow configuration
to be skipped based on the presence or absence of specific classes. Due to the fact that
annotation meta-data is parsed using ASM you can actually use the `value` attribute to
refer to the real class, even though that class might not actually appear in the running
application classpath. You can also use the `name` attribute if you prefer to specify
the class name using a `String` value.
###Bean conditions
The `@ConditionalOnBean` and `@ConditionalOnMissingBean` annotations allow configuration
to be skipped based on the presence or absence of specific beans. You can use the `value`
attribute to specify beans by type, or `name` to specify beans by name. The `search`
attribute allows you to limit the `ApplicationContext` hierarchy that should be considered
when searching for beans.
> **Note:** `@Conditional` annotations are processed when `@Configuration` classes are
parsed. Auto-configure `@Configuration` is always parsed last (after any user defined
beans), however, if you are using these annotations on regular `@Configuration` classes,
care must be take not to refer to bean definitions that have not yet been created.
###Resource conditions
The `@ConditionalOnResource` annotation allows configuration to be skipped when a specific
resource is not present. Resources can be specified using the usual Spring conventions,
for example, `file:C:/test.dat`.
###Web Application Conditions
The `@ConditionalOnWebApplication` and `@ConditionalOnNotWebApplication` annotations
allow configuration to be skipped depending on whether the application is a
'web application'. A web application is any application that is using a Spring
`WebApplicationContext`, defines a `session` scope or has a `StandardServletEnvironment`.
###SpEL expression conditions
The `@ConditionalOnExpression` annotation allows configuration to be skipped based on the
result of a SpEL expression.
##Writing additional auto-configuration
You can easily add auto-configuration to your own libraries, simply create a regular
`@Configuration` class and annotate it with appropriate `@Conditional` restrictions.
Spring Boot checks for presence of a `META-INF/spring.factories` file within your
published jar. The file should list your configuration classes under the
`org.springframework.boot.autoconfigure.EnableAutoConfiguration` key.
```
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration
```
You can use the `@AutoConfigureAfter` or `@AutoConfigureBefore` annotations if your
configuration needs to be applied in a specific order. For example, if you provide
web specific configuration you may need to be applied after `WebMvcAutoConfiguration`.
#Further reading
For more information about any of the classes or interfaces discussed in the document
please refer to the extensive project Javadoc. If you are just starting out with Spring
Boot take a look at the [getting started](../README.md) guide.

View File

@ -1,215 +0,0 @@
# Spring Boot - CLI
## Installing the CLI
You need [Java SDK v1.6](http://www.java.com) or higher to run the command line tool
(there are even some issues with the `1.7.0_25` build of openjdk, so stick to earlier
builds or use `1.6` for preference). You should check your current Java installation
before you begin:
$ java -version
### Manual installation
You can download the Spring CLI distribution from the Spring software repository:
* [spring-boot-cli-1.0.0.RC4-bin.zip](http://repo.spring.io/milestone/org/springframework/boot/spring-boot-cli/1.0.0.RC4/spring-boot-cli-1.0.0.RC4-bin.zip)
* [spring-boot-cli-1.0.0.RC4-bin.tar.gz](http://repo.spring.io/milestone/org/springframework/boot/spring-boot-cli/1.0.0.RC4/spring-boot-cli-1.0.0.RC4-bin.tar.gz)
Cutting edge [snapshot distributions](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/)
are also available.
Once downloaded, follow the
[INSTALL](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-cli/src/main/content/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,
or alternatively you can use `java -jar` with the `.jar` file (the
script helps you to be sure that the classpath is set correctly).
### Installation with GVM
GVM (the Groovy Environment Manager) can be used for managing multiple
versions of verious Groovy and Java binary packages, including Groovy
itself and the Spring Boot CLI. Get `gvm` from
[the gvm home page](http://gvmtool.net) and install Spring Boot with
$ gvm install springboot
$ spring --version
Spring Boot v1.0.0.RC4
> **Note:** If you are developing features for the CLI and want easy access to the version you just built, follow these extra instructions.
$ gvm install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-1.0.0.BUILD-SNAPSHOT-bin/spring-1.0.0.BUILD-SNAPSHOT/
$ gvm use springboot dev
$ spring --version
Spring CLI v1.0.0.BUILD-SNAPSHOT
This will install a local instance of `spring` called the `dev` instance inside your gvm repository. It points at your target build location, so every time you rebuild Spring Boot, `spring` will be up-to-date.
You can see it by doing this:
$ gvm ls springboot
```
================================================================================
Available Springboot Versions
================================================================================
> + dev
* 1.0.0.RC4
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
```
### OSX Homebrew installation
If you are on a Mac and using [homebrew](http://brew.sh/), all you need to do to install
the Spring Boot CLI is:
```
$ brew install http://repo.spring.io/install/spring-boot-cli.rb
```
Homebrew will install `spring` to `/usr/local/bin`. Now you can jump right to a
[quick start example](#quick-start-script-example).
> **Note:** If you don't see the formula, you're installation of brew might be
> out-of-date. Just execute `brew update` and try again.
### Quick start script example
Here's a really simple web application. Create a file called `app.groovy`:
```groovy
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
return "Hello World!"
}
}
```
Then run it from a shell:
```
$ spring run app.groovy
```
> **Note:** It will take some time when you first run the application as dependencies
> are downloaded, subsequent runs will be much quicker.
Open [http://localhost:8080](http://localhost:8080) in your favorite web browser and you
should see the following output:
> Hello World!
## Testing Your Code
The Spring Boot CLI has a `test` command. Example usage:
```
$ spring test app.groovy tests.groovy
Total: 1, Success: 1, : Failures: 0
Passed? true
```
Where `tests.groovy` contains JUnit `@Test` methods or Spock
`Specification` classes. All the common framework annotations and
static methods should be available to you without having to import
them. Example with JUnit (for the above application):
```groovy
class ApplicationTests {
@Test
void homeSaysHello() {
assertEquals("Hello World", new ThisWillActuallyRun().home())
}
}
```
You can add more tests by adding additional
files, or you might prefer to put them in a special directory.
## Applications with Multiple Source Files
You can use shell globbing to pick up multiple files in a single
directory, e.g.
```
$ spring run *.groovy
```
and this enables you to easily segregate your test or spec code from
the main application code, if that's what you prefer, e.g.
```
$ spring test app/*.groovy test/*.groovy
```
## Beans DSL
Spring has native support for a `beans{}` DSL (borrowed from
[Grails](http://grails.org)), and you can embedd bean definitions in
your Groovy application scripts using the same format. This is
sometimes a good way to include external features like middleware
declarations. E.g.
```groovy
@Configuration
class Application implements CommandLineRunner {
@Autowired
SharedService service
@Override
void run(String... args) {
println service.message
}
}
import my.company.SharedService
beans {
service(SharedService) {
message "Hello World"
}
}
```
You can mix class declarations with `beans{}` in the same file as long
as they stay at the top level, or you can put the beans DSL in a
separate file if you prefer.
## Commandline Completion
Spring Boot CLI ships with a script that provides command completion
in a standard bash-like shell. 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 `/etc/bash_completion.d` and all scripts in that directory are
executed in a new shell. To run the script manually, e.g. if you have
installed using GVM
```
$ . ~/.gvm/springboot/current/bash_completion.d/spring
$ spring <HIT TAB HERE>
clean -d debug help run test version
```
## Packaging Your Application
You can use the `jar` command to package your application into a
self-contained executable jar file. For example:
```
$ spring jar my-app.jar *.groovy
```
The resulting jar will containe the classes produced by compiling
the application and all of the application's dependencies such that
it can then be run using `java -jar`. The jar file will also contain
entries from the application's classpath. See the output of
`spring help jar` for more information.

View File

@ -1,4 +0,0 @@
# Spring Boot - Samples
> We are currently still working on documentation for Spring Boot. Please check back
> in the future.

View File

@ -1,23 +0,0 @@
# Spring Boot Actuator Sample
You can build this sample using Maven (>3) or Gradle (1.6).
With Maven:
```
$ mvn package
$ java -jar target/*.jar
```
Then access the app via a browser (or curl) on http://localhost:8080 (the user name is
"user" and look at the INFO log output for the password to login).
With gradle:
```
$ gradle build
$ java -jar build/libs/*.jar
```
The gradle build contains an intentionally odd configuration to exclude the security
dependencies from the executable JAR. So the app run like this behaves differently than
the one run from the Maven-built JAR file. See comments in the `build.gradle` for details.

View File

@ -1,21 +0,0 @@
# Spring Boot Actuator Sample
You can build this sample using Maven (>3) or Gradle (1.6).
With Maven:
```
$ mvn package
$ java -jar target/*.jar
```
Then access the app via a browser (or curl) on http://localhost:8080 (the user name is "user" and look at the INFO log output for the password to login).
With gradle:
```
$ gradle build
$ java -jar build/libs/*.jar
```
The gradle build contains an intentionally odd configuration to exclude the security dependencies from the executable JAR. So the app run like this behaves differently than the one run from the Maven-built JAR file. See comments in the `build.gradle` for details.

View File

@ -1,19 +0,0 @@
# Spring Boot Simple Sample
You can build this sample using Maven (>3) or Gradle (1.6).
With Maven:
```
$ mvn package
$ java -jar target/*.jar
```
The app prints a Hello message on the console.
With gradle:
```
$ gradle build
$ java -jar build/libs/*.jar
```

View File

@ -1,211 +0,0 @@
# Spring Boot - 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.
## Building a Spring Boot Project with Maven
The quickest way to get started with a new project is to use the
spring-boot-starter-parent, e.g.
```xml
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.0.RC4</version>
</parent>
```
The parent pom adds two main fetaures to your project:
* dependency management configuration, so you don't have to specify
versions or excludes with your own dependencies, as long as they are
part of the Spring Boot stack
* plugin configuration, so you don't have to configure some common
settings in the main Maven plugins used to get a project off the
ground (e.g. the
[Spring Boot Maven plugin](../spring-boot-tools/spring-boot-maven-plugin/README.md))
As an example, if you want to build a simple RESTful web service with
embedded Tomcat, you only need one dependency:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
And if you want to use the Spring Boot plugin to package the project
as an executable JAR (or run it from source code), you only need to
add the plugin (not configure it, unless you want to change the
settings in the parent):
```xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
```
If you need to access milestone or snapshot builds from Spring
projects, you can optionallyt add repositories, as follows:
```xml
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
```
The repositories cannot all be defined in the parent (at least one
will be required to resolve the parent itself).
### Using Your Own Parent POM
If you don't want to use the Spring Boot starter parent, you can use
your own and still keep the benefit of the dependency management (but
not the plugin management) using
["scope=import"](http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html). Example:
```xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.0.RC4</version>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
```
(It actually doesn't matter if you use "spring-boot-starter-parent" or
"spring-boot-dependencies".)
### Samples
All the
[Spring Boot Samples](../spring-boot-samples)
come with a `pom.xml`, but they use a different parent to
spring-boot-starter-parent (although that pom is one of their
ancestors). Other useful places to get clean projects with a
`pom.xml` that works as quickly as possible:
* The
[Getting Started Guides on spring.io](http://spring.io/guides/gs) are
all available in [github](https://github.com/spring-guides), or you
can copy paste from the guides themselves (all the code is on the web
page).
* The same guides are available as working projects in
[Spring Tool Suite](http://spring.io/tools/sts)(STS) (an Eclipse
plugin feature set), and so is a starter project template generator
(via `File->New->Spring Starter Project`).
* The Spring Starter Project feature in STS is backed by a web
application at [start.spring.io](http://start.spring.io), which you
can also use yourself to download ZIP files of the starter projects.
## Building With Gradle
If you prefer to build your project with Gradle then similar features
are available to you as to Maven users. The starter projects work in
exactly the same way, for instance, so a typical project might have a
`build.gradle` like this:
```groovy
buildscript {
ext {
springBootVersion = '1.0.0.RC4'
}
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'spring-boot'
jar {
baseName = 'spring-boot-sample-simple'
version = '0.5.0'
}
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-milestone" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
task wrapper(type: Wrapper) { gradleVersion = '1.6' }
```
This build is for a simple RESTful web service (with embedded
Tomcat). Notice that the dependencies do not have explicit version
numbers. This works for Spring Boot dependencies, but also anything
else that is explicitly managed by the Spring Boot Starter parent.
Versionless dependency resolution is a feature of the
[Spring Boot Gradle Plugin](../spring-boot-tools/spring-boot-gradle-plugin/README.md),
which also gives you a "run from source" feature ("gradle bootRun")
and an enhanced JAR/WAR packaging feature for executable archives
("gradle build").
### Samples
Most of the samples mentioned above for Maven users are also buildable
using Gradle. Only some of the
[Spring Boot Samples](../spring-boot-samples)
come with a `build.gradle`. The Spring Starter Project feature in STS
produces a Maven project. But web application at
[start.spring.io](http://start.spring.io) can generate Gradle build
files for the same projects (just download it with a browser or
command line).

View File

@ -1,10 +0,0 @@
# Spring Boot - Tools
Spring Boot Tools provides a logical grouping for our various build system plugins, and
the modules that support them. We provide a
[spring-boot-maven-plugin](spring-boot-maven-plugin) and
[spring-boot-gradle-plugin](spring-boot-gradle-plugin) for Maven and Gradle respectively.
If you are interested in how we support executable archives, take a look at the
[spring-boot-loader](spring-boot-loader) module. If you need to create executable
archives from a different build system,
[spring-boot-loader-tools](spring-boot-loader-tools) may help.

View File

@ -1,4 +0,0 @@
# Spring Boot - Dependency Tools
The Spring Boot Dependency Tools module provides support utilities to help when resolving
'blessed' Spring Boot dependencies. It basically provides programmatic access to the
managed dependencies section of `spring-boot-dependencies/pom.xml`

View File

@ -1,192 +0,0 @@
# Spring Boot - Gradle Plugin
The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, allowing you to
package executable jar or war archives, run Spring Boot applications and remove version
information from your `build.gradle` file.
## Including the plugin
To use the Spring Boot Gradle Plugin simply include a `buildscript` dependency and apply
the `spring-boot` plugin:
```groovy
buildscript {
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:{{project.version}}")
}
}
apply plugin: 'spring-boot'
```
If you are using a milestone or snapshot release you will also need to add appropriate
`repositories` reference:
```groovy
buildscript {
repositories {
maven.url "http://repo.spring.io/snapshot"
maven.url "http://repo.spring.io/milestone"
}
// ...
}
```
## Declaring dependencies without versions
The `spring-boot` plugin will register a custom Gradle `ResolutionStrategy` with your
build that allows you to omit version numbers when declaring dependencies to known
artifacts. All artifacts with a `org.springframework.boot` group ID, and any of the
artifacts declared in the `managementDependencies` section of the `spring-dependencies`
POM can have their version number resolved automatically.
Simply declare dependencies in the usual way, but leave the version number empty:
```groovy
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.thymeleaf:thymeleaf-spring4")
compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")
}
```
## Packaging executable jar and war files
Once the `spring-boot` plugin has been applied to your project it will automatically
attempt to rewrite archives to make them executable using the `bootRepackage` task. You
should configure your project to build a jar or war (as appropriate) in the usual way.
The main class that you want to launch can either be specified using a configuration
option, or by adding a `Main-Class` attribute to the manifest. If you don't specify a
main class the plugin will search for a class with a
`public static void main(String[] args)` method.
To build and run a project artifact, you do something like this:
```
$ gradle build
$ java -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar
```
### Running a Project in Place
To run a project in place without building a jar first you can use the "bootRun" task:
```
$ gradle bootRun
```
Running this way makes your static classpath resources (i.e. in
`src/main/resources` by default) reloadable in the live application,
which can be helpful at development time.
### Repackage configuration
The gradle plugin automatically extends your build script DSL with a `springBoot` element
for configuration. Simply set the appropriate properties as you would any other gradle
extension:
```groovy
springBoot {
backupSource = false
}
```
### Repackage with Custom Gradle Configuration
Sometimes it may be more appropriate to not package default dependencies resolved from
`compile`, `runtime` and `provided` scopes. If created executable jar file
is intended to be run as it is you need to have all dependencies in it, however
if a plan is to explode a jar file and run main class manually you may already
have some of the libraries available via `CLASSPATH`. This is a situation where
you can repackage boot jar with a different set of dependencies. Using a custom
configuration will automatically disable dependency resolving from
`compile`, `runtime` and `provided` scopes. Custom configuration can be either
defined globally inside `springBoot` or per task.
```groovy
task clientJar(type: Jar) {
appendix = 'client'
from sourceSets.main.output
exclude('**/*Something*')
}
task clientBoot(type: BootRepackage, dependsOn: clientJar) {
withJarTask = clientJar
customConfiguration = "mycustomconfiguration"
}
```
In above example we created a new `clientJar` Jar task to package a customized
file set from your compiled sources. Then we created a new `clientBoot`
BootRepackage task and instructed it to work with only `clientJar` task and
`mycustomconfiguration`.
```groovy
configurations {
mycustomconfiguration.exclude group: 'log4j'
}
dependencies {
mycustomconfiguration configurations.runtime
}
```
Configuration we are referring to in `BootRepackage` is a normal
Gradle configuration. In above example we created a new configuration
named `mycustomconfiguration` instructing it to derive from a `runtime`
and exclude `log4j` group. If `clientBoot` task is executed, repackaged
boot jar will have all dependencies from a runtime but no
log4j jars.
The following configuration options are available:
| Name | Type | Description | Default Value |
|-----------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------|
| mainClass | String | The main class that should be run. If not specified the value from the manifest will be used, or if no manifest entry is the archive will be searched for a suitable class | |
| providedConfiguration | String | The name of the provided configuration | providedRuntime |
| backupSource | boolean | If the original source archive should be backed-up before being repackaged | true |
| customConfiguration | String | The name of the custom configuration | none |
| layout | String | The type of archive (which corresponds to how the dependencies are layed out inside it). Defaults to a guess based on the archive type. |
## Further Reading
For more information on how Spring Boot Loader archives work, take a look at the
[spring-boot-loader](../spring-boot-loader/README.md) module. If you prefer using Maven to
build your projects we have a [spring-boot-maven-plugin](../spring-boot-maven-plugin/README.md).
### Understanding how Boot Gradle Plugin Works
When `spring-boot` is applied to your Gradle project a default task
named `bootRepackage` is created automatically. Boot repackage task
depends on Gradle `assemble` task and when executed, it tries to find
all jar artifacts whose qualifier is empty(meaning i.e. tests and
sources jars are automatically skipped).
Because on default every repackage task execution will find all
created jar artifacts, the order of Gradle task execution is
important. This is not going to be an issue if you have a normal
project setup where only one jar file is created. However if you are
planning to create more complex project setup with custom Jar and
BootRepackage tasks, there are few tweaks to consider.
```groovy
jar.enabled = false
bootRepackage.enabled = false
```
Above example simply disables default `jar` and `bootRepackage` tasks.
This would be all right if you are just creating custom jar files
out from your project. You could also just disable default
`bootRepackage` task.
```groovy
bootRepackage.withJarTask = jar
```
Above example simply instructs default `bootRepackage` task to only
work with a default `jar` task.
```groovy
task bootJars
bootJars.dependsOn = [clientBoot1,clientBoot2,clientBoot3]
build.dependsOn(bootJars)
```
If you still have a default project setup where main jar file is
created and repackaged to be used with boot and you still want to
create additional custom jar files out from your project, you
could simple combine you custom repackage tasks together and
create dependency to your build so that `bootJars` task would
be run after the default `bootRepackage` task is executed.
All the above tweaks are usually used to avoid situation where
already created boot jar is repackaged again. Repackaging
an existing boot jar will not break anything but you may
get unnecessary dependencies in it.

View File

@ -1,52 +0,0 @@
# Spring Boot - Loader Tools
The Spring Boot Loader Tools module provides support utilities to help when creating
[Spring Boot Loader](../spring-boot-loader/README.md) compatible archives. This module is
used by the various build system plugins that we provide.
> **Note:** The quickest way to build a compatible archive is to use the
> [spring-boot-maven-plugin](../spring-boot-maven-plugin/README.md) or
> [spring-boot-gradle-plugin](../spring-boot-gradle-plugin/README.md).
## 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.
## Libraries
When repackaging an archive you can include references to dependency files using the
`org.springframework.boot.loader.tools.Libraries` interface. We don't 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`
## Finding a main class
If you don't use `Repackager.setMainClass()` to specify a main class, the repackager will
use [ASM](http://asm.ow2.org/) to read class files and attempt to find a suitable class.
The first class with a `public static void main(String[] args)` method will be used.
Searching is performed using a breadth first algorithm, with the assumption that the main
class will appear high in the package structure.
## Example
Here is a typical example repackage:
```java
Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(false);
repackager.repackage(new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
// Build system specific implementation, callback for each dependency
// callback.library(nestedFile, LibraryScope.COMPILE);
}
});
```
## Further Reading
For more information on how Spring Boot Loader archives work take a look at the
[spring-boot-loader](../spring-boot-loader/README.md) module. If you want to see how we use this
library the [Maven](../spring-boot-maven-plugin/README.md) and
[Gradle](../spring-boot-gradle-plugin/README.md) plugins are good place to start.

View File

@ -1,228 +0,0 @@
# Spring Boot - Loader
The Spring Boot Loader module allows JAR and WAR files that contain
nested dependencies to be run using `java -jar archive.jar`. There are
3 launcher classes (`JarLauncher`, `WarLauncher` and
`PropertiesLauncher`). Their purpose is to load resources (.class
files etc.) from nested JAR files or JAR files in directories (as
opposed to explicitly on the classpath). In the case of the
`[Jar|War]Launcher` the nested paths are fixed `(lib/*.jar` and
`lib-provided/*.jar` for the WAR case) so you just add extra JARs in
those locations if you want more. The `PropertiesLauncher` looks in
`lib/` by default, but you can add additional locations by setting an
environment variable `LOADER_PATH`or `loader.path` in
`application.properties` (colon-separated list of directories or archives).
> **Note:** The quickest way to build a compatible archive is to use the
> [spring-boot-maven-plugin](../spring-boot-maven-plugin/README.md) or
> [spring-boot-gradle-plugin](../spring-boot-gradle-plugin/README.md).
## Nested JARs
Java does not provide any standard way to load nested jar files (i.e. jar files that
are themselves contained within a jar). This can be problematic if you are looking
to distribute a self contained application that you can just run from the command line
without unpacking.
To solve this problem, many developers use 'shaded' jars. A shaded jar simply 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 you are actually using in your application.
It can also be problematic if the the same filename is used (but with different content)
in multiple jars. Spring Boot takes a different approach and allows you to actually nest
jars directly.
### JAR file structure
Spring Boot Loader compatible jar files should be structured in the following way:
```
example.jar
|
+-META-INF
| +-MANIFEST.MF
+-org
| +-springframework
| +-boot
| +-loader
| +-<spring boot loader classes>
+-com
| +-mycompany
| + project
| +-YouClasses.class
+-lib
+-dependency1.jar
+-dependency2.jar
```
Dependencies should be placed in a nested `lib` directory.
See [executable-jar](src/it/executable-jar) for an example project.
### WAR file structure
Spring Boot Loader compatible war files should be structured in the following way:
```
example.jar
|
+-META-INF
| +-MANIFEST.MF
+-org
| +-springframework
| +-boot
| +-loader
| +-<spring boot loader classes>
+-WEB-INF
+-classes
| +-com
| +-mycompany
| +-project
| +-YouClasses.class
+-lib
| +-dependency1.jar
| +-dependency2.jar
+-lib-provided
+-servlet-api.jar
+-dependency3.jar
```
Dependencies should be placed in a nested `WEB-INF/lib` directory. Any dependencies
that are required when running embedded but are not required when deploying to
a traditional web container should be placed in `WEB-INF/lib-provided`.
See [executable-war](src/it/executable-war) for an example project.
## RandomAccessJarFile
The core class used to support loading nested jars is
`org.springframework.boot.loader.jar.RandomAccessJarFile`. It allows 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:
```
myapp.jar
+---------+---------------------+
| | /lib/mylib.jar |
| A.class |+---------+---------+|
| || B.class | B.class ||
| |+---------+---------+|
+---------+---------------------+
^ ^ ^
0063 3452 3980
```
The example above shows how `A.class` can be found in `myapp.jar` position `0063`.
`B.class` from the nested jar can actually be found in `myapp.jar` position `3452`
and `B.class` is at position `3980`.
Armed with this information, we can load specific nested entries by simply seeking to
appropriate part if the outer jar. We don't need to unpack the archive and we don't
need to read all entry data into memory.
### Compatibility
Spring Boot Loader strives to remain compatible with existing code and libraries. The
`RandomAccessJarFile` extends from `java.util.jar.JarFile` and should work as a drop-in
replacement. The `RandomAccessJarFile.getURL()` method will return a `URL` that opens
a `java.net.JarURLConnection` compatible connection. `RandomAccessJarFile` URLs can
be used with Java's `URLClassLoader`.
## Launching
The `org.springframework.boot.loader.Launcher` class can be used to run your packaged
application. It takes care of setting up an appropriate `URLClassLoader` and calling
your `main()` method.
### Launcher manifest
You need specify an appropriate `Launcher` as the `Main-Class` attribute of
`META-INF/MANIFEST.MF`. The actual class that you want to launch (i.e. the class that
you wrote that contains a `main` method) should be specified in the `Start-Class`
attribute.
For example, here is a typical `MANIFEST.MF` for a executable jar file:
```
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.mycompany.project.MyApplication
```
For a war file, it would be:
```
Main-Class: org.springframework.boot.loader.WarLauncher
Start-Class: com.mycompany.project.MyApplication
```
> **Note:** You do not need to specify `Class-Path` entries in your manifest file, the
> classpath will be deduced from the nested jars.
### Exploded archives
Certain PaaS implementations may choose to unpack archives before they run. For example,
Cloud Foundry operates in this way. You can run an unpacked archive by simply starting
the appropriate launcher:
```
$ unzip -q myapp.jar
$ java org.springframework.boot.loader.JarLauncher
```
## PropertiesLauncher Features
`PropertiesLauncher` has a few special features that can be enabled
with external properties (System properties, environment variables,
manifest entries or `application.properties`).
| Key | Purpose | Typical value |
|------------|---------|---------------|
|loader.path |Classpath (colon-separated) |lib:${HOME}/app/lib|
|loader.home |Location of additional properties file (defaults to `${user.dir}`) |file:///opt/app|
|loader.args |Default arguments for the main method (space separated) ||
|loader.main |Name of main class to launch | com.app.Application |
|loader.config.name|Name of properties file (default "application") | loader|
|loader.config.location|Path to properties file (default "application/.properties") | classpath:loader.properties|
|loader.system|Boolean flag to indicate that all properties should be added to System properties (default false)|true|
Manifest entry keys are formed by capitalizing intial letters of words
and changing the separator to '-' from '.' (e.g. "Loader-Path"). The
exception is "loader.main" which is looked up as "Start-Class" in the
manifest for compatibility with `JarLauncher`).
Environment variables can be capitalized with underscore separators
instead of periods.
* `loader.home` is the directory location of an additional properties
file (overriding the default) as long as `loader.config.location` is
not specified
* `loader.path` can contain directories (scanned recursively for jar
and zip files), archive paths, or wildcard patterns (for the default
JVM behaviour)
* Placeholder replacement is done from System and environment
variables plus the properties file itself on all values before use.
## Restrictions
There are a number of restrictions that you need to consider when working with a Spring
Boot Loader packaged application.
### Zip entry compression
The `ZipEntry` for a nested jar must be saved 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. You can use the Spring Boot
[Maven](../spring-boot-maven-plugin/README.md) or
[Gradle](../spring-boot-gradle-plugin/README.md) plugins
to ensure that your archives are written correctly.
### System ClassLoader
Launched applications should use `Thread.getContextClassLoader()` when loading classes
(most libraries and frameworks will do this by default). Trying to load nested jar
classes via `ClassLoader.getSystemClassLoader()` will fail. Please be aware that
`java.util.Logging` always uses the system classloader, for this reason you should
consider a different logging implementation.
### Alternatives
If the above restrictions mean that you cannot use Spring Boot Loader the following
alternatives could be considered:
* [Maven Shade Plugin](http://maven.apache.org/plugins/maven-shade-plugin/)
* [JarClassLoader](http://www.jdotsoft.com/JarClassLoader.php)
* [OneJar](http://one-jar.sourceforge.net)
## Further Reading
For more information about any of the classes or interfaces discussed in the document
please refer to the project Javadoc. If you need to build a compatible archives see the
[spring-boot-maven-plugin](../spring-boot-maven-plugin/README.md) or
[spring-boot-gradle-plugin](../spring-boot-gradle-plugin/README.md). If you are not using
Maven or Gradle [spring-boot-loader-tools](../spring-boot-loader-tools/README.md) provides
some useful utilities to rewite existing zip files.

View File

@ -1,185 +0,0 @@
# Spring Boot - Maven Plugin
The Spring Boot Maven Plugin provides Spring Boot support in Maven,
allowing you to package executable jar or war archives and run an
application in-place. To use it you must be using Maven 3 (or better).
## Including the plugin
To use the Spring Boot Maven Plugin simply include the appropriate XML in the `plugins`
section of your `pom.xml`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- ... -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>{{project.version}}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
This configuration will repackage a JAR or WAR that is built in the
"package" phase of the Maven lifecycle, so
```
$ mvn package
$ ls target/*.jar
target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original
```
will reveal the result. If you don't include the `<execution/>`
configuration as above you can run the plugin on its own, but only if
the package goal is used as well, e.g.
```
$ mvn package spring-boot:repackage
```
will have the same effect as above.
If you are using a milestone or snapshot release you will also need to add appropriate
`pluginRepository` elements:
```xml
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
```
## Packaging executable jar and war files
Once `spring-boot-maven-plugin` has been included in your `pom.xml` it will
automatically attempt to rewrite archives to make them executable using the
`spring-boot:repackage` goal. You should configure your project to build a jar or war
(as appropriate) using the usual `packaging` element:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- ... -->
<packaging>jar</packaging>
<!-- ... -->
</project>
```
Your existing archive will be enhanced by Spring Boot during the `package`
phase. The main class that you want to launch can either be specified using a
configuration option, or by adding a `Main-Class` attribute to the manifest in the usual
way. If you don't specify a main class the plugin will search for a class with a
`public static void main(String[] args)` method.
To build and run a project artifact, you do something like this:
```
$ mvn package
$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar
```
### Repackage configuration
The following configuration options are available for the `spring-boot:repackage` goal:
**Required Parameters**
| Name | Type | Description | Default Value |
|-----------------|--------|--------------------------------------------|----------------------------|
| outputDirectory | File | Directory containing the generated archive | ${project.build.directory} |
| finalName | String | Name of the generated archive | ${project.build.finalName} |
**Optional Parameters**
| Name | Type | Description |
|-----------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| classifier | String | Classifier to add to the artifact generated. If given, the artifact will be attached. If this is not given, it will merely be written to the output directory according to the finalName |
| mainClass | String | The name of the main class. If not specified the first compiled class found that contains a 'main' method will be used |
| layout | String | The type of archive (which corresponds to how the dependencies are layed out inside it). Defaults to a guess based on the archive type. |
The plugin rewrites your manifest, and in particular it manages the
`Main-Class` and `Start-Class` entries, so if the defaults don't work
you have to configure those there (not in the jar plugin). The
`Main-Class` in the manifest is actually controlled by the `layout`
property of the boot plugin, e.g.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>{{project.version}}</version>
<configuration>
<mainClass>${start-class}</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
The layout property defaults to a guess based on the archive type (JAR
or WAR). For the `PropertiesLauncher` the layout is "ZIP" (even though
the output might be a JAR file).
## Running applications
The Spring Boot Maven Plugin includes a `run` goal which can be used to launch your
application from the command line. Type the following from the root of your maven
project:
```
$ mvn spring-boot:run
```
By default, any `src/main/resources` folder will be added to the application classpath
when you run via the maven plugin. This allows hot refreshing of resources which can be
very useful when web applications. For example, you can work on HTML, CSS or JavaScipt
files and see your changes immediately without recompiling your application. It is also
a helpful way of allowing your front end developers to work without needing to download
and install a Java IDE.
### Run configuration
The following configuration options are available for the `spring-boot:run` goal:
**Required Parameters**
| Name | Type | Description | Default Value |
|--------------------------------------|---------|----------------------------------------------------------------------------------------------|----------------------------------|
| classesDirectrory | File | Directory containing the classes and resource files that should be packaged into the archive | ${project.build.outputDirectory} |
**Optional Parameters**
| Name | Type | Description | Default Value |
|--------------------------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------|
| arguments (or -Drun.arguments) | String[] | Arguments that should be passed to the application | |
| addResources (or -Drun.addResources) | boolean | Add maven resources to the classpath directly, this allows live in-place editing or resources. Since resources will be added directly, and via the target/classes folder they will appear twice if ClassLoader.getResources() is called. In practice however most applications call ClassLoader.getResource() which will always return the first resource | true |
| mainClass | String | The name of the main class. If not specified the first compiled class found that contains a 'main' method will be used | |
| folders | String[] | Folders that should be added to the classpath | ${project.build.outputDirectory} |
## Further Reading
For more information on how Spring Boot Loader archives work, take a look at the
[spring-boot-loader](../spring-boot-loader/README.md) module. If you prefer using Gradle to
build your projects we have a [spring-boot-gradle-plugin](../spring-boot-gradle-plugin/README.md).

View File

@ -1,516 +0,0 @@
# Spring Boot - Core
This module provides the core features for the other modules in the project. It is
relatively unopinionated and it has minimal required dependencies which makes it usable
as a stand-alone library for anyone whose tastes diverge from ours.
## SpringApplication
The `SpringApplication` class provides a convenient way to bootstrap a Spring application
that will be started from a `main()` method. In many situations you can just delegate
to the static `SpringApplication.run` method:
```java
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class, args);
}
```
When you application starts you should see something similar to the following:
```
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: v0.0.0.BUILD.SNAPSHOT
2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
```
By default `INFO` logging messages will shown, including some relevant startup details
such as the user that launched the application.
### Customizing SpringApplication
If the SpringApplication defaults aren't to your taste you can instead create a local
instance and customize it. For example, to turn off the banner you would write:
```java
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setShowBanner(false);
app.run(args);
}
```
Note that the constructor arguments passed to `SpringApplication` are configuration
sources for spring beans. In most cases these will be references to `@Configuration`
classes, but they could also be references to XML configuration or to packages that
should be scanned.
See the `SpringApplication` Javadoc for a complete list of the configuration options
### Accessing command line properties
By default `SpringApplication` will convert any command line option arguments (starting
with '--', e.g. `--server.port=9000`) to a `PropertySource` and add it to the Spring
`Environment` with highest priority (taking precedence and overriding values from other
sources). Properties in the `Environment` (including System properties and OS environment
variables) can always be injected into Spring components using `@Value` with
placeholders, e.g.
```java
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*
@Component
public class MyBean {
@Value("${name}")
private String name;
// Running 'java -jar myapp.jar --name=Spring' will set this to "Spring"
// ...
}
```
### CommandLineRunner beans
If you want access to the raw command line argument, or you need to run some specific
code once the `SpringApplication` has started you can implement the `CommandLineRunner`
interface. The `run(String... args)` method will be called on all spring beans
implementing this interface.
```java
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
```
You can additionally implement the `org.springframework.core.Ordered` interface or use
the `org.springframework.core.annotation.Order` annotation if several `CommandLineRunner`
beans are defined that must be called in a specific order.
### Application Exit
Each `SpringApplication` will register a shutdown hook with the JVM to ensure that the
`ApplicationContext` is closed gracefully on exit. All the standard Spring lifecycle
callbacks (such as the `DisposableBean` interface, or the `@PreDestroy` annotation)
can be used.
In addition, beans may implement the `org.springframework.boot.ExitCodeGenerator`
interface if they wish to return a specific exit code when the application ends.
### Externalized Configuration
A `SpringApplication` will load properties from `application.properties` in the root of
your classpath and add them to the Spring `Environment`. The actual search path for the
files is:
1. classpath root
2. current directory
3. classpath `/config` package
4. `/config` subdir of the current directory.
The list is ordered by decreasing precedence (so properties can be overridden by others
with the same name defined in later locations). In addition, profile specific properties
can also be defined using the naming convention `application-{profile}.properties`
(properties from these files override the default ones).
The values in `application.properties` are filtered through the existing `Environment`
when they are used so you can refer back to previously defined values (e.g. from System
properties).
```
app.name: MyApp
app.description: ${app.name} is a Spring Boot application
```
If you don't like `application.properties` as the configuration file name you can
switch to another by specifying `spring.config.name` environment property. You can also
refer to an explicit location using the `spring.config.location` environment property.
$ java -jar myproject.jar --spring.config.name=myproject
> **Note:** You can also use '.yml' files as an alternative to '.properties' (see
> [below](#using-yaml-instead-of-properties))_
### Setting the Default Spring Profile
Spring Profiles are a way to segregate parts of the application configuration and make it
only available in certain environments. Any `@Component` that is marked with `@Profile`
will only be loaded in the profile specified by the latter annotation.
A `SpringApplication` takes this a stage further, in that you can use a
`spring.profiles.active` `Environment` property to specify which profiles are active.
You can specify the property in any of the usual ways, for example you could include
it in your `application.properties`:
```
spring.profiles.active=dev,hsqldb
```
or specify on the command line using the switch `--spring.profiles.active=dev,hsqldb`.
#### Adding active profiles
The `spring.profiles.active` property follows the same ordering rules as other
properties, the highest `PropertySource` will win. This means that you can specify
active profiles in `application.properties` then **replace** them using the command line
switch.
Sometimes it is useful to have profile specific properties that **add** to the active
profiles rather than replace them. The `+` prefix can be used to add active profiles.
For example, when an application with following properties is run using the switch
`--spring.profiles.active=prod` the `proddb` and `prodmq` profiles will also be activated:
```yaml
---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.active: +proddb,+prodmq
```
### Application Context Initializers
Spring provides a convenient `ApplicationContextInitializer` interface that can be used
to customize an `ApplicationContext` before it is used. If you need to use an initializer
with your `SpringApplication` you can use the `addInitializers` method.
You can also specify initializers by setting comma-delimited list of class names to the
`Environment` property `context.initializer.classes` or by using Spring's
`SpringFactoriesLoader` mechanism.
## Embedded Servlet Container Support
Spring Boot introduces a new type of Spring `ApplicationContext` that can be used to
start an embedded servlet container. The `EmbeddedWebApplicationContext` is a special
type of `WebApplicationContext` that starts the container by searching for a single
`EmbeddedServletContainerFactory` bean contained within itself. We provide
`TomcatEmbeddedServletContainerFactory` and `JettyEmbeddedServletContainerFactory`
implementations for running embedded Tomcat or Jetty.
One advantage of using a Spring bean to define the embedded container is that you can use
all the standard Spring concepts. For example, it becomes trivial to define a Tomcat
server that sets its port from an injected `@Value`.
```java
@Configuration
public class MyConfiguration {
@Value("${tomcatport:8080}")
private int port;
@Bean
public EmbeddedServletContainerFactory servletContainer() {
return new TomcatEmbeddedServletContainerFactory(this.port);
}
}
```
### Customizing Servlet Containers
Both the Tomcat and Jetty factories extend from the base
`AbstractEmbeddedServletContainerFactory` class. This provides a uniform way
to configure both containers.
Settings that you would traditionally configure in a `web.xml` or via an implementation
specific configuration file can now be performed programmatically.
```java
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setPort(9000);
factory.setSessionTimeout(10, TimeUnit.MINUTES);
factory.addErrorPages(new ErrorPage(HttpStatus.404, "/notfound.html");
return factory;
}
```
In addition, you can also add `ServletContextInitializer` implementations which allow
you to customize the `javax.servlet.ServletContext` in the same way as any Servlet 3.0
environment.
### Servlets and Filters
Servlets and Filters can be defined directly as beans with the
`EmbeddedWebApplicationContext`. By default, if the context contains only a single
Servlet it will be mapped to '/'. In the case of multiple Servlets beans the bean name
will be used as a path prefix. Filters will map to '/*'.
If convention based mapping is not flexible enough you can use the
`ServletRegistrationBean` and `FilterRegistrationBean` classes for complete control. You
can also register items directly if your bean implements the `ServletContextInitializer`
interface.
### JSP limitations
When running a Spring Boot application that uses
an embedded servlet container (and is packaged as an executable
archive), there are some limitations in the JSP support.
* With Tomcat it should work if you use WAR packaging, i.e. an
executable WAR will work, and will also be deployable to a standard
container (not limited to, but including Tomcat). An executable JAR
will not work because of a hard coded file pattern in Tomcat.
* Jetty does not currently work as an embedded container with
JSPs. There should be a way to make it work, so hopefully someone
can figure it out (pull requests always welcome).
There is a
[JSP sample](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp)
so you can see how to set things up.
## Using YAML instead of Properties
[YAML](http://yaml.org) is a superset of JSON, and as such is a very convenient format
for specifying hierarchical configuration data. The `SpringApplication` class will
automatically support YAML as an alternative to properties whenever you have the
[SnakeYAML](http://code.google.com/p/snakeyaml/) library on your classpath.
### Loading YAML
Spring Boot provides two convenient classes that can be used to load YAML documents. The
`YamlPropertiesFactoryBean` will load YAML as `Properties` and the `YamlMapFactoryBean`
will load YAML as a `Map`.
For example, the following YAML document:
```yaml
dev:
url: http://dev.bar.com
name: Developer Setup
prod:
url: http://foo.bar.com
name: My Cool App
```
Would be transformed into these properties:
```
environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App
```
YAML lists are represented as comma-separated values (useful for simple String values)
and also as property keys with `[index]` dereferencers, for example this YAML:
```yaml
servers:
- dev.bar.com
- foo.bar.com
```
Would be transformed into these properties:
```
servers=dev.bar.com,foo.bar.com
servers[0]=dev.bar.com
servers[1]=foo.bar.com
```
### Exposing YAML as properties in the Spring Environment.
The `YamlPropertySourceLoader` class can be used to expose YAML as a `PropertySource`
in the Spring `Environment`. This allows you to the familiar `@Value` with placeholders
syntax to access YAML properties.
You can also specify multiple profile-specific YAML document in a single file by
by using a `spring.profiles` key to indicate when the document applies. For example:
```yaml
server:
address: 192.168.1.100
---
spring:
profiles: production
server:
address: 192.168.1.120
```
### YAML shortcomings
YAML files can't (currently) be loaded via the `@PropertySource` annotation. So in the case
that you need to load values that way, you need to use a properties file.
## Typesafe Configuration Properties
Use the `@Value("${property}")` annotation to inject configuration properties can
sometimes be cumbersome, especially if you are working with multiple properties or
your data is hierarchical in nature. Spring Boot provides an alternative method
of working with properties that allows strongly typed beans to govern and validate
the configuration of your application. For example:
```java
@Component
@ConfigurationProperties(name="connection")
public class ConnectionSettings {
private String username;
private InetAddress remoteAddress;
// ... getters and setters
}
```
When the `@EnableConfigurationProperties` annotation is applied to your `@Configuration`,
any beans annotated with `@ConfigurationProperties` will automatically be configured
from the `Environment` properties. This style of configuration works particularly well
with the `SpringApplication` external YAML configuration:
```yaml
# application.yml
connection:
username: admin
remoteAddress: 192.168.1.1
# additional configuration as required
```
To work with `@ConfigurationProperties` beans you can just inject them in the same way
as any other bean.
```java
@Service
public class MyService {
@Autowired
private ConnectionSettings connection;
//...
@PostConstruct
public void openConnection() {
Server server = new Server();
this.connection.configure(server);
}
}
```
It is also possible to shortcut the registration of `@ConfigurationProperties` bean
definitions by simply listing the properties classes directly in the
`@EnableConfigurationProperties` annotation:
```java
@Configuration
@EnableConfigurationProperties(ConnectionSettings.class)
public class MyConfiguration {
}
```
### Relaxed binding
Spring Boot uses some relaxed rules for binding `Environment` properties to
`@ConfigurationProperties` beans, so there doesn't need to be an exact match between
the `Environment` property name and the bean property name. Common examples where this
is useful include underscore separated (e.g. `context_path` binds to `contextPath`), and
capitalized (e.g. `PORT` binds to `port`) environment properties.
Spring will attempt to coerce the external application properties to the right type when
it binds to the `@ConfigurationProperties` beans. If you need custom type conversion you
can provide a `ConversionService` bean (with bean id `conversionService`) or custom
property editors (via a `CustomEditorConfigurer` bean).
### @ConfigurationProperties Validation
Spring Boot will attempt to validate external configuration, by default using JSR-303
(if it is on the classpath). You can simply add JSR-303 `javax.valididation` constraint
annotations to your `@ConfigurationProperties` class:
```java
@Component
@ConfigurationProperties(name="connection")
public class ConnectionSettings {
@NotNull
private InetAddress remoteAddress;
// ... getters and setters
}
```
You can also add a custom Spring `Validator` by creating a bean definition called
`configurationPropertiesValidator`.
### Using Project Lombok
You can safely use [Project Lombok](http://projectlombok.org) to generate getters and
setters for your `@ConfigurationProperties`. Refer to the documentation on the Lombok
for how to enable it in your compiler or IDE.
### External EmbeddedServletContainerFactory configuration
Spring Boot includes a `@ConfigurationProperties` annotated class called
`ServerProperties` that can be used to configure the `EmbeddedServletContainerFactory`.
When registered as a bean, the `ServerProperties` can be used to specify:
* The port that the application listens on for its endpoints
(`server.port` defaults to `8080`)
* The address that the application endpoints are available on
(`server.address` defaults to all local addresses, making it available to connections
from all clients).
* The context root of the application endpoints (`server.context_path`
defaults to '/')
If you are using Tomcat as you embedded container then, in addition to the
generic `ServerProperties`, you can also bind `server.tomcat.*` properties
to specify:
* The Tomcat access log pattern (`server.tomcat.accessLogPattern`)
* The remote IP and protocol headers (`server.tomcat.protocolHeader`,
`server.tomcat.remoteIpHeader`)
* The Tomcat `base directory` (`server.tomcat.basedir`)
## Customizing Logging
Spring Boot uses [Commons Logging](commons.apache.org/logging) for all internal logging,
but leaves the underlying log implementation open. Default configurations are provided for
[Java Util Logging](http://docs.oracle.com/javase/7/docs/api/java/util/logging/package-summary.html),
[Log4J](http://logging.apache.org/log4j/) and [Logback](http://logback.qos.ch/).
In each case there is console output and file output (rotating, 10MB file size).
The various logging systems can be activated by including the appropriate libraries on
the classpath, and further customized by supported by providing a suitable configuration
file in the root of the classpath, or in a location specified by the Spring `Environment`
property `logging.config`.
Depending on your logging system, the following files will be loaded:
|Logging System|Customization |
|--------------|-------------------------------|
|Logback | logback.xml |
|Log4j | log4j.properties or log4j.xml |
|JDK | logging.properties |
To help with the customization some other properties are transferred from the Spring
`Environment` to System properties:
|Environment |System Property |Comments |
|-------------|----------------|---------------------------------------------------------------------------|
|logging.file |LOG_FILE | Used in default log configuration if defined |
|logging.path |LOG_PATH | Used in default log configuration if defined |
|PID |PID | The current process ID is discovered if possible and not already provided |
All the logging systems supported can consult System properties when parsing their
configuration files. See the default configurations in `spring-boot.jar` for examples.
## Cloud Foundry Support
When a `SpringApplication` is deployed to [Cloud Foundry](http://www.cloudfoundry.com/)
appropriate meta-data will be exposed as `Environemnt` properties. All Cloud Foundry
properties are prefixed `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 `ApplicationContextInitializer` Javdoc for complete details.
## Further Reading
For more information about any of the classes or interfaces discussed in the document
please refer to the extensive project Javadoc. If looking to reduce the amount of
configuration required for your application you should consider
[spring-boot-autoconfigure](../spring-boot-autoconfigure/README.md). For operational
concerns see [spring-boot-actuator](../spring-boot-actuator/README.md). For details on
how to package your application into a single executable JAR file take a look at
[spring-boot-loader](../spring-boot-loader/README.md).