It is strongly recommended that you choose a build system that supports dependency management, and one that can consume artifacts published to the ``Maven Central'' repository. We would recommend that you choose Maven or Gradle. It is possible to get Spring Boot to work with other build systems (Ant for example), but they will not be particularly well supported.
Maven users can inherit from the spring-boot-starter-parent
project to obtain sensible
defaults. The parent project provides the following features:
-
Java 1.6 as the default compiler level.
-
UTF-8 source encoding.
-
A Dependency Management section, allowing you to omit
<version>
tags for common dependencies, inherited from thespring-boot-dependencies
POM. -
Sensible resource filtering.
-
Sensible plugin configuration (exec plugin, surefire, Git commit ID, shade).
To configure your project to inherit from the spring-boot-starter-parent
simply set
the parent
:
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{spring-boot-version}</version>
</parent>
Note
|
You should only need to specify the Spring Boot version number on this dependency. If you import additional starters, you can safely omit the version number. |
Not everyone likes inheriting from the spring-boot-starter-parent
POM. You may have your
own corporate standard parent that you need to use, or you may just prefer to explicitly
declare all your Maven configuration.
If you don’t want to use the spring-boot-starter-parent
, you can still keep the benefit
of the dependency management (but not the plugin management) by using a scope=import
dependency:
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>{spring-boot-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The spring-boot-starter-parent
chooses fairly conservative Java compatibility. If you
want to follow our recommendation and use a later Java version you can add a
java.version
property:
<properties>
<java.version>1.8</java.version>
</properties>
Spring Boot includes a Maven plugin
that can package the project as an executable jar. Add the plugin to your <plugins>
section if you want to use it:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Note
|
If you use the Spring Boot starter parent pom, you only need to add the plugin, there is no need for to configure it unless you want to change the settings defined in the parent. |
Gradle users can directly import starter POMs'' in their
super parent'' to import to share some configuration.dependencies
section. Unlike
Maven, there is no
apply plugin: 'java'
repositories { jcenter() }
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:{spring-boot-version}")
}
The spring-boot-gradle-plugin
is also available and provides tasks to create executable jars and run projects from
source. It also adds a ResolutionStrategy
that enables you to
omit the version number
for ``blessed'' dependencies:
buildscript {
repositories { jcenter() }
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-version}")
}
}
apply plugin: 'java'
apply plugin: 'spring-boot'
repositories { jcenter() }
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
It is possible to build a Spring Boot project using Apache Ant, however, no special support or plugins are provided. Ant scripts can use the Ivy dependency system to import starter POMs.
See the 'howto.adoc' ``How-to'' for more complete instructions.
Starter POMs 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.
All starters follow a similar naming pattern; spring-boot-starter-
, where is
a particular type of application. This naming structure is intended to help when you need
to find a starter. The Maven integration in many IDEs allow you to search dependencies by
name. For example, with the appropriate Eclipse or STS plugin installed, you can simply
hit
ctrl-space
in the POM editor and type ''spring-boot-starter'' for a complete list.
The following application starters are provided by Spring Boot under the
org.springframework.boot
group:
Name | Description |
---|---|
|
The core Spring Boot starter, including auto-configuration support, logging and YAML. |
|
Support for the |
|
Support for aspect-oriented programming including |
|
Support for ``Spring Batch'' including HSQLDB database. |
|
Support for the Elasticsearch search and analytics engine including
|
|
Support for the GemFire distributed data store including |
|
Support for the |
|
Support for the MongoDB NoSQL Database, including |
|
Support for exposing Spring Data repositories over REST via |
|
Support for the Apache Solr search platform, including |
|
Support for the FreeMarker templating engine |
|
Support for the Groovy templating engine |
|
Support for ``Java Message Service API'' via HornetQ. |
|
Support for common |
|
JDBC Database support. |
|
Support for JTA distributed transactions via Atomikos. |
|
Support for JTA distributed transactions via Bitronix. |
|
Support for |
|
Support for the REDIS key-value data store, including |
|
Support for |
|
Support for |
|
Support for |
|
Support for |
|
Support for common test dependencies, including JUnit, Hamcrest and Mockito along with
the |
|
Support for the Thymeleaf templating engine, including integration with Spring. |
|
Support for the Velocity templating engine |
|
Support for full-stack web development, including Tomcat and |
|
Support for websocket development with Tomcat. |
|
Support for Spring Web Services |
In addition to the application starters, the following starters can be used to add 'production ready' features.
Name | Description |
---|---|
|
Adds production ready features such as metrics and monitoring. |
|
Adds remote |
Finally, Spring Boot includes some starters that can be used if you want to exclude or swap specific technical facets.
Name | Description |
---|---|
|
Imports the Jetty HTTP engine (to be used as an alternative to Tomcat) |
|
Support the Log4J logging framework |
|
Import Spring Boot’s default logging framework (Logback). |
|
Import Spring Boot’s default HTTP engine (Tomcat). |
Tip
|
For a list of additional community contributed starter POMs, see the
{github-master-code}/spring-boot-starters/README.adoc[README file] in the
spring-boot-starters module on GitHub.
|
Spring Boot does not require any specific code layout to work, however, there are some best practices that help.
When a class doesn’t include a package
declaration it is considered to be in the
default package''. The use of the
default package'' is generally discouraged, and
should be avoided. It can cause particular problems for Spring Boot applications that
use @ComponentScan
or @EntityScan
annotations, since every class from every jar,
will be read.
Tip
|
We recommend that you follow Java’s recommended package naming conventions
and use a reversed domain name (for example, com.example.project ).
|
We generally recommend that you locate your main application class in a root package
above other classes. The @EnableAutoConfiguration
annotation is often placed on your
main class, and it implicitly defines a base `search package'' for certain items. For
example, if you are writing a JPA application, the package of the
`@EnableAutoConfiguration
annotated class will be used to search for @Entity
items.
Using a root package also allows the @ComponentScan
annotation to be used without
needing to specify a basePackage
attribute.
Here is a typical layout:
com +- example +- myproject +- Application.java | +- domain | +- Customer.java | +- CustomerRepository.java | +- service | +- CustomerService.java | +- web +- CustomerController.java
The Application.java
file would declare the main
method, along with the basic
@Configuration
.
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring Boot favors Java-based configuration. Although it is possible to call
SpringApplication.run()
with an XML source, we generally recommend that your primary
source is a @Configuration
class. Usually the class that defines the main
method
is also a good candidate as the primary @Configuration
.
Tip
|
Many Spring configuration examples have been published on the Internet that use XML
configuration. Always try to use the equivalent Java-base configuration if possible.
Searching for enable* annotations can be a good starting point.
|
You don’t need to put all your @Configuration
into a single class. The @Import
annotation can be used to import additional configuration classes. Alternatively, you
can use @ComponentScan
to automatically pickup all Spring components, including
@Configuration
classes.
Spring Boot auto-configuration attempts to automatically configure your Spring
application based on the jar dependencies that you have added. For example, If
HSQLDB
is on your classpath, and you have not manually configured any database
connection beans, then we will auto-configure an in-memory database.
You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration
annotation to one of your @Configuration
classes.
Tip
|
You should only ever add one @EnableAutoConfiguration annotation. We generally
recommend that you add it to your primary @Configuration class.
|
Auto-configuration is noninvasive, at any point you can start to define your own
configuration to replace specific parts of the auto-configuration. For example, if
you add your own DataSource
bean, the default embedded database support will back away.
If you need to find out what auto-configuration is currently being applied, and why,
starting your application with the --debug
switch. This will log an auto-configuration
report to the console.
If you find that specific auto-configure classes are being applied that you don’t want,
you can use the exclude attribute of @EnableAutoConfiguration
to disable them.
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
You are free to use any of the standard Spring Framework techniques to define your beans
and their injected dependencies. For simplicity, we often find that using @ComponentScan
to find your beans, in combination with @Autowired
constructor injection works well.
If you structure your code as suggested above (locating your application class in a root
package), you can add @ComponentScan
without any arguments. All of your application
components (@Component
, @Service
, @Repository
, @Controller
etc.) will be
automatically registered as Spring Beans.
Here is an example @Service
Bean that uses constructor injection to obtain a
required RiskAssessor
bean.
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
Tip
|
Notice how using constructor injection allows the riskAssessor field to be marked
as final , indicating that it cannot be subsequently changed.
|
One of the biggest advantages of packaging your application as jar and using an embedded HTTP server is that you can run your application as you would any other. Debugging Spring Boot applications is also easy; you don’t need any special IDE plugins or extensions.
Note
|
This section only covers jar based packaging, If you choose to package your application as a war file you should refer to your server and IDE documentation. |
You can run a Spring Boot application from your IDE as a simple Java application, however,
first you will need to import your project. Import steps will vary depending on your IDE
and build system. Most IDEs can import Maven projects directly, for example Eclipse users
can select Import…
→ Existing Maven Projects
from the File
menu.
If you can’t directly import your project into your IDE, you may be able to generate IDE meta-data using a build plugin. Maven includes plugins for Eclipse and IDEA; Gradle offers plugins for various IDEs.
Tip
|
If you accidentally run a web application twice you will see a `Port already in
use'' error. STS users can use the `Relaunch button rather than Run to ensure that
any existing instance is closed.
|
If you use the Spring Boot Maven or Gradle plugins to create an executable jar you can
run your application using java -jar
. For example:
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
It is also possible to run a packaged application with remote debugging support enabled. This allows you to attach a debugger to your packaged application:
$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ -jar target/myproject-0.0.1-SNAPSHOT.jar
The Spring Boot Maven plugin includes a run
goal which can be used to quickly compile
and run your application. Applications run in an exploded form, and you can edit
resources for instant ``hot'' reload.
$ mvn spring-boot:run
Useful operating system environment variable:
$ export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom
(The ``egd'' setting is to speed up Tomcat startup by giving it a faster source of entropy for session keys.)
The Spring Boot Gradle plugin also includes a run
goal which can be used to run
your application in an exploded form. The bootRun
task is added whenever you import
the spring-boot-plugin
$ gradle bootRun
Useful operating system environment variable:
$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom
Since Spring Boot applications are just plain Java applications, JVM hot-swapping should work out of the box. JVM hot swapping is somewhat limited with the bytecode that it can replace, for a more complete solution the Spring Loaded project, or JRebel can be used.
See the Hot swapping ``How-to'' section for details.
Executable jars can be used for production deployment. As they are self contained, they are also ideally suited for cloud-based deployment.
For additional `production ready'' features, such as health, auditing and metric REST
or JMX end-points; consider adding `spring-boot-actuator
. See
'production-ready-features.adoc' for details.
You should now have good understanding of how you can use Spring Boot along with some best practices that you should follow. You can now go on to learn about specific 'Spring Boot features' in depth, or you could skip ahead and read about the ``production ready'' aspects of Spring Boot.