SpringBoot 2.1.2 Keys

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 87

What

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you
can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get
started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

Spring Boot 2.1.2.RELEASE requires Java 8 and is compatible up to Java 11 (included). Spring
Framework 5.1.4.RELEASE or above is also required.

Containers

Spring Boot supports the following embedded servlet containers:

Name Servlet Version

Tomcat 9.0 4.0

Jetty 9.4 3.1

Undertow 2.0 4.0

You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container.

Building

Spring Boot dependencies use the org.springframework.boot groupId. Typically, your Maven
POM file inherits from the spring-boot-starter-parent project and declares dependencies to one
or more “Starters”. Spring Boot also provides an optional Maven plugin to create executable jars.

Spring Boot dependencies can be declared by using the org.springframework.boot group.


Typically, your project declares dependencies to one or more “Starters”. Spring Boot provides a useful
Gradle plugin that can be used to simplify dependency declarations and to create executable jars.

Upgrading from an Earlier Version of Spring Boot


If you are upgrading from an earlier release of Spring Boot, check the “migration guide” on the project
wiki that provides detailed upgrade instructions. Check also the“release notes” for a list of “new and
noteworthy” features for each release.

The @RestController and @RequestMapping Annotations


The first annotation on our Example class is @RestController. This is known as a stereotype
annotation. It provides hints for people reading the code and for Spring that the class plays a specific
role. In this case, our class is a web @Controller, so Spring considers it when handling incoming
web requests.

The @RequestMapping annotation provides “routing” information. It tells Spring that any HTTP
request with the / path should be mapped to the home method. The@RestController annotation
tells Spring to render the resulting string directly back to the caller.

The @RestController and @RequestMapping annotations are Spring MVC annotations. (They are
not specific to Spring Boot.)

The @EnableAutoConfiguration Annotation


The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring
Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added.
Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration
assumes that you are developing a web application and sets up Spring accordingly.

Starters and Auto-configuration

Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You
are free to pick and choose jar dependencies outside of the starters. Spring Boot still does its best to
auto-configure your application.

The “main” Method


The final part of our application is the main method. This is just a standard method that follows the Java
convention for an application entry point. Our main method delegates to Spring Boot’s
SpringApplication class by calling run. SpringApplication bootstraps our application,
starting Spring, which, in turn, starts the auto-configured Tomcat web server. We need to pass
Example.class as an argument to the run method to tell SpringApplication which is the
primary Spring component. The args array is also passed through to expose any command-line
arguments.

Creating an Executable Jar


To create an executable jar, we need to add the spring-boot-maven-plugin to our pom.xml.
To do so, insert the following lines just below the dependenciessection:

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Using the Spring Boot Maven Plugin


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, as shown in the following example:

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

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

Starters
Starters are a set of convenient dependency descriptors that you can include in your application. You get
a one-stop shop for all the Spring and related technologies that you need without having to hunt through
sample code and copy-paste loads of dependency descriptors.

The starters contain a lot of the dependencies that you need to get a project up and running quickly and
with a consistent, supported set of managed transitive dependencies.

The following application starters are provided by Spring Boot under the
org.springframework.boot group:

Table 13.1. Spring Boot application starters


Name Description Pom

spring-boot-starter Core starter, including auto-configuration Pom


support, logging and YAML

spring-boot-starter-activemq Starter for JMS messaging using Apache Pom


ActiveMQ

spring-boot-starter-amqp Starter for using Spring AMQP and Rabbit MQ Pom

spring-boot-starter-aop Starter for aspect-oriented programming with Pom


Spring AOP and AspectJ

spring-boot-starter-artemis Starter for JMS messaging using Apache Pom


Artemis

spring-boot-starter-batch Starter for using Spring Batch Pom

spring-boot-starter-cache Starter for using Spring Framework’s caching Pom


support

spring-boot-starter-cloud- Starter for using Spring Cloud Connectors Pom


connectors which simplifies connecting to services in cloud
platforms like Cloud Foundry and Heroku

spring-boot-starter-data- Starter for using Cassandra distributed Pom


cassandra database and Spring Data Cassandra

spring-boot-starter-data- Starter for using Cassandra distributed Pom


cassandra-reactive database and Spring Data Cassandra Reactive

spring-boot-starter-data- Starter for using Couchbase document-oriented Pom


couchbase database and Spring Data Couchbase

spring-boot-starter-data- Starter for using Couchbase document-oriented Pom


couchbase-reactive database and Spring Data Couchbase Reactive
spring-boot-starter-data- Starter for using Elasticsearch search and Pom
elasticsearch analytics engine and Spring Data Elasticsearch

spring-boot-starter-data- Starter for using Spring Data JDBC Pom


jdbc

spring-boot-starter-data-jpa Starter for using Spring Data JPA with Pom


Hibernate

spring-boot-starter-data- Starter for using Spring Data LDAP Pom


ldap

spring-boot-starter-data- Starter for using MongoDB document-oriented Pom


mongodb database and Spring Data MongoDB

spring-boot-starter-data- Starter for using MongoDB document-oriented Pom


mongodb-reactive database and Spring Data MongoDB Reactive

spring-boot-starter-data- Starter for using Neo4j graph database and Pom


neo4j Spring Data Neo4j

spring-boot-starter-data- Starter for using Redis key-value data store Pom


redis with Spring Data Redis and the Lettuce client

spring-boot-starter-data- Starter for using Redis key-value data store Pom


redis-reactive with Spring Data Redis reactive and the Lettuce
client

spring-boot-starter-data- Starter for exposing Spring Data repositories Pom


rest over REST using Spring Data REST

spring-boot-starter-data- Starter for using the Apache Solr search Pom


solr platform with Spring Data Solr

spring-boot-starter- Starter for building MVC web applications using Pom


freemarker FreeMarker views
spring-boot-starter-groovy- Starter for building MVC web applications using Pom
templates Groovy Templates views

spring-boot-starter-hateoas Starter for building hypermedia-based RESTful Pom


web application with Spring MVC and Spring
HATEOAS

spring-boot-starter- Starter for using Spring Integration Pom


integration

spring-boot-starter-jdbc Starter for using JDBC with the HikariCP Pom


connection pool

spring-boot-starter-jersey Starter for building RESTful web applications Pom


using JAX-RS and Jersey. An alternative to
spring-boot-starter-web

spring-boot-starter-jooq Starter for using jOOQ to access SQL Pom


databases. An alternative to spring-boot-
starter-data-jpa or spring-boot-
starter-jdbc

spring-boot-starter-json Starter for reading and writing json Pom

spring-boot-starter-jta- Starter for JTA transactions using Atomikos Pom


atomikos

spring-boot-starter-jta- Starter for JTA transactions using Bitronix Pom


bitronix

spring-boot-starter-mail Starter for using Java Mail and Spring Pom


Framework’s email sending support

spring-boot-starter-mustache Starter for building web applications using Pom


Mustache views
spring-boot-starter-oauth2- Starter for using Spring Security’s Pom
client OAuth2/OpenID Connect client features

spring-boot-starter-oauth2- Starter for using Spring Security’s OAuth2 Pom


resource-server resource server features

spring-boot-starter-quartz Starter for using the Quartz scheduler Pom

spring-boot-starter-security Starter for using Spring Security Pom

spring-boot-starter-test Starter for testing Spring Boot applications with Pom


libraries including JUnit, Hamcrest and Mockito

spring-boot-starter- Starter for building MVC web applications using Pom


thymeleaf Thymeleaf views

spring-boot-starter- Starter for using Java Bean Validation with Pom


validation Hibernate Validator

spring-boot-starter-web Starter for building web, including RESTful, Pom


applications using Spring MVC. Uses Tomcat
as the default embedded container

spring-boot-starter-web- Starter for using Spring Web Services Pom


services

spring-boot-starter-webflux Starter for building WebFlux applications using Pom


Spring Framework’s Reactive Web support

spring-boot-starter- Starter for building WebSocket applications Pom


websocket using Spring Framework’s WebSocket support

In addition to the application starters, the following starters can be used to add production
ready features:

Table 13.2. Spring Boot production starters


Name Description Pom

spring- Starter for using Spring Boot’s Actuator which provides P


boot- production ready features to help you monitor and manage o

starter- your application m

actuator

Finally, Spring Boot also includes the following starters that can be used if you want to
exclude or swap specific technical facets:

Table 13.3. Spring Boot technical starters

Name Description Pom

spring-boot- Starter for using Jetty as the embedded servlet container. An Pom
starter-jetty alternative to spring-boot-starter-tomcat

spring-boot- Starter for using Log4j2 for logging. An alternative to spring- Pom
starter-log4j2 boot-starter-logging

spring-boot- Starter for logging using Logback. Default logging starter Pom
starter-logging

spring-boot- Starter for using Reactor Netty as the embedded reactive HTTP Pom
starter-reactor- server.
netty

spring-boot- Starter for using Tomcat as the embedded servlet container. Pom
starter-tomcat Default servlet container starter used by spring-boot-
starter-web

spring-boot- Starter for using Undertow as the embedded servlet container. An Pom
starter-undertow alternative to spring-boot-starter-tomcat
Structuring Your Code
Spring Boot does not require any specific code layout to work. However, there are some
best practices that help.

Using the “default” Package


When a class does not include a package declaration, it is considered to be in the “default
package”. The use of the “default package” is generally discouraged and should be avoided.
It can cause particular problems for Spring Boot applications that use the
@ComponentScan, @EntityScan, or @SpringBootApplicationannotations,
since every class from every jar is read.

We recommend that you follow Java’s recommended package


naming conventions and use a reversed domain name (for
example, com.example.project).

Locating the Main Application Class


We generally recommend that you locate your main application class in a root package
above other classes. The @SpringBootApplication annotation is often placed on
your main class, and it implicitly defines a base “search package” for certain items. For
example, if you are writing a JPA application, the package of the
@SpringBootApplication annotated class is used to search for @Entity items.
Using a root package also allows component scan to apply only on your project.

If you don’t want to use @SpringBootApplication, the

@EnableAutoConfiguration and @ComponentScan annotations


that it imports defines that behaviour so you can also use that instead.

The following listing shows a typical layout:

com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java

The Application.java file would declare the main method, along with the basic
@SpringBootApplication, as follows:

package com.example.myapplication;

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

@SpringBootApplication
public class Application {

public static void main(String[] args) {


SpringApplication.run(Application.class, args);
}

}
Configuration Classes
Spring Boot favors Java-based configuration. Although it is possible to use
SpringApplication with XML sources, we generally recommend that your primary
source be a single @Configuration class. Usually the class that defines the main
method is a good candidate as the primary @Configuration.

Many Spring configuration examples have been published on


the Internet that use XML configuration. If possible, always try to
use the equivalent Java-based configuration. Searching for
Enable* annotations can be a good starting point.

Importing Additional Configuration Classes


You need not put all your @Configuration into a single class. The @Import annotation
can be used to import additional configuration classes. Alternatively, you can use
@ComponentScan to automatically pick up all Spring components, including
@Configuration classes.

Auto-configuration
Spring Boot auto-configuration attempts to automatically configure your Spring application
based on the jar dependencies that you have added. For example, if HSQLDBis on your
classpath, and you have not manually configured any database connection beans, then
Spring Boot auto-configures an in-memory database.

You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or


@SpringBootApplication annotations to one of your @Configurationclasses.
You should only ever add one @SpringBootApplication or

@EnableAutoConfiguration annotation. We generally recommend that


you add one or the other to your primary @Configuration class only.

Gradually Replacing Auto-configuration


Auto-configuration is non-invasive. At any point, you can start to define your own
configuration to replace specific parts of the auto-configuration. For example, if you add your
own DataSource bean, the default embedded database support backs away.

If you need to find out what auto-configuration is currently being applied, and why, start your
application with the --debug switch. Doing so enables debug logs for a selection of core
loggers and logs a conditions report to the console.

Disabling Specific Auto-configuration Classes


If you find that specific auto-configuration classes that you do not want are being applied,
you can use the exclude attribute of @EnableAutoConfiguration to disable them, as
shown in the following example:

import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

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

If the class is not on the classpath, you can use the excludeName attribute of the
annotation and specify the fully qualified name instead. Finally, you can also control the list
of auto-configuration classes to exclude by using the
spring.autoconfigure.exclude property.

Spring Beans and Dependency Injection


You are free to use any of the standard Spring Framework techniques to define your beans
and their injected dependencies. For simplicity, we often find that using@ComponentScan
(to find your beans) and using @Autowired (to do constructor injection) works well.
If you structure your code as suggested above (locating your application class in a root
package), you can add @ComponentScan without any arguments. All of your application
components (@Component, @Service, @Repository, @Controller etc.) are
automatically registered as Spring Beans.

The following example shows a @Service Bean that uses constructor injection to obtain a
required RiskAssessor bean:

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;
}

// ...

If a bean has one constructor, you can omit the @Autowired, as shown in the following
example:

@Service
public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

public DatabaseAccountService(RiskAssessor riskAssessor) {


this.riskAssessor = riskAssessor;
}

// ...

}
Notice how using constructor injection lets the riskAssessor

field be marked as final, indicating that it cannot be


subsequently changed.

Using the @SpringBootApplication Annotation


Many Spring Boot developers like their apps to use auto-configuration, component scan and
be able to define extra configuration on their "application class". A
single@SpringBootApplication annotation can be used to enable those three
features, that is:

● @EnableAutoConfiguration: enable Spring Boot’s auto-configuration


mechanism
● @ComponentScan: enable @Component scan on the package where the
application is located (see the best practices)
● @Configuration: allow to register extra beans in the context or import additional
configuration classes

The @SpringBootApplication annotation is equivalent to using @Configuration,


@EnableAutoConfiguration, and @ComponentScan with their default attributes, as
shown in the following example:

package com.example.myapplication;

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

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration


@ComponentScan
public class Application {

public static void main(String[] args) {


SpringApplication.run(Application.class, args);
}
}

@SpringBootApplication also provides aliases to


customize the attributes of @EnableAutoConfiguration

and @ComponentScan.

None of these features are mandatory and you may choose to replace this single
annotation by any of the features that it enables. For instance, you may not want to
use component scan in your application:
package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan
import
org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class Application {

public static void main(String[] args) {


SpringApplication.run(Application.class,
args);
}

In this example, Application is just like any other Spring Boot application except

that @Component-annotated classes are not detected automatically and the user-

defined beans are imported explicitly (see @Import).

Running Your Application


One of the biggest advantages of packaging your application as a jar and using an
embedded HTTP server is that you can run your application as you would any other.
Debugging Spring Boot applications is also easy. You do not need any special IDE plugins
or extensions.

Using the Gradle Plugin


The Spring Boot Gradle plugin also includes a bootRun task that can be used to run your
application in an exploded form. The bootRun task is added whenever you apply the
org.springframework.boot and java plugins and is shown in the following
example:
$ gradle bootRun

You might also want to use the JAVA_OPTS operating system environment variable, as
shown in the following example:

$ export JAVA_OPTS=-Xmx1024m

Developer Tools
Spring Boot includes an additional set of tools that can make the application development
experience a little more pleasant. The spring-boot-devtools module can be included
in any project to provide additional development-time features. To include devtools support,
add the module dependency to your build, as shown in the following listings for Maven and
Gradle:

Maven.

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

Gradle.

configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
dependencies {
developmentOnly("org.springframework.boot:spring-boot-devtools")
}
Developer tools are automatically disabled when running a fully
packaged application. If your application is launched from java

-jar or if it is started from a special classloader, then it is


considered a “production application”. Flagging the dependency
as optional in Maven or using a custom`developmentOnly`
configuration in Gradle (as shown above) is a best practice that
prevents devtools from being transitively applied to other
modules that use your project.

Repackaged archives do not contain devtools by default. If you


want to use a certain remote devtools feature, you need to
disable the excludeDevtoolsbuild property to include it.
The property is supported with both the Maven and Gradle
plugins.

SpringApplication
The SpringApplication class provides a convenient way to bootstrap a Spring
application that is started from a main() method. In many situations, you can delegate to
the static SpringApplication.run method, as shown in the following example:

public static void main(String[] args) {


SpringApplication.run(MySpringConfiguration.class, args);
}

Startup Failure
If your application fails to start, registered FailureAnalyzers get a chance to provide a
dedicated error message and a concrete action to fix the problem. For instance, if you start a
web application on port 8080 and that port is already in use, you should see something
similar to the following message:

***************************
APPLICATION FAILED TO START
***************************

Description:

Embedded servlet container failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure
this application to listen on another port.

If no failure analyzers are able to handle the exception, you can still display the full
conditions report to better understand what went wrong. To do so, you need to enable the
debug property or enable DEBUG logging for
org.springframework.boot.autoconfigure.logging.ConditionEvalua
tionReportLoggingListener.

For instance, if you are running your application by using java -jar, you can enable the
debug property as follows:

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

Customizing the Banner


The banner that is printed on start up can be changed by adding a banner.txt file to your
classpath or by setting the spring.banner.location property to the location of such
a file. If the file has an encoding other than UTF-8, you can set
spring.banner.charset. In addition to a text file, you can also add a banner.gif,
banner.jpg, or banner.png image file to your classpath or set the
spring.banner.image.location property. Images are converted into an ASCII art
representation and printed above any text banner.

Inside your banner.txt file, you can use any of the following placeholders:

Table 23.1. Banner variables

Variable Description

${application.version} The version number of your


application, as declared in
MANIFEST.MF. For
example,Implementation

-Version: 1.0 is printed


as 1.0.

${application.formatted-version} The version number of your


application, as declared in
MANIFEST.MF and
formatted for display
(surrounded with brackets
and prefixed with v). For

example (v1.0).

${spring-boot.version} The Spring Boot version that


you are using. For example
2.1.2.RELEASE.

${spring-boot.formatted-version} The Spring Boot version that


you are using, formatted for
display (surrounded with
brackets and prefixed with v).
For example
(v2.1.2.RELEASE).

${Ansi.NAME} (or ${AnsiColor.NAME}, $ Where NAME is the name of

{AnsiBackground.NAME}, $ an ANSI escape code. See

{AnsiStyle.NAME}) AnsiPropertySource for


details.

${application.title} The title of your application,


as declared in
MANIFEST.MF. For
exampleImplementation

-Title: MyApp is printed


as MyApp.

The SpringApplication.setBanner(…) method can


be used if you want to generate a banner programmatically. Use
the org.springframework.boot.Banner interface and

implement your own printBanner() method.

You can also use the spring.main.banner-mode property to determine if the banner
has to be printed on System.out (console), sent to the configured logger (log), or not
produced at all (off).

The printed banner is registered as a singleton bean under the following name:
springBootBanner.
YAML maps off to false, so be sure to add quotes if you
want to disable the banner in your application, as shown in the
following example:

spring:
main:
banner-mode: "off"

In my case what i did is create a txt file in the resources folder and set the property in spring
spring.banner.location = classpath:/banner.txt

Application Events and Listeners


In addition to the usual Spring Framework events, such as ContextRefreshedEvent, a
SpringApplication sends some additional application events.

Some events are actually triggered before the ApplicationContext is


created, so you cannot register a listener on those as a @Bean. You can register

them with the SpringApplication.addListeners(…) method or the

SpringApplicationBuilder.listeners(…) method.

If you want those listeners to be registered automatically, regardless of the way


the application is created, you can add a META-INF/spring.factoriesfile
to your project and reference your listener(s) by using the
org.springframework.context.ApplicationListener key, as
shown in the following example:

org.springframework.context.ApplicationListener=com.exampl
e.project.MyListener

Application events are sent in the following order, as your application runs:

1. An ApplicationStartingEvent is sent at the start of a run but before any


processing, except for the registration of listeners and initializers.
2. An ApplicationEnvironmentPreparedEvent is sent when the
Environment to be used in the context is known but before the context is created.
3. An ApplicationPreparedEvent is sent just before the refresh is started but
after bean definitions have been loaded.
4. An ApplicationStartedEvent is sent after the context has been refreshed but
before any application and command-line runners have been called.
5. An ApplicationReadyEvent is sent after any application and command-line
runners have been called. It indicates that the application is ready to service
requests.
6. An ApplicationFailedEvent is sent if there is an exception on startup.

You often need not use application events, but it can be handy
to know that they exist. Internally, Spring Boot uses events to
handle a variety of tasks.

Application events are sent by using Spring Framework’s event publishing mechanism. Part
of this mechanism ensures that an event published to the listeners in a child context is also
published to the listeners in any ancestor contexts. As a result of this, if your application
uses a hierarchy of SpringApplication instances, a listener may receive multiple
instances of the same type of application event.

To allow your listener to distinguish between an event for its context and an event for a
descendant context, it should request that its application context is injected and then
compare the injected context with the context of the event. The context can be injected by
implementing ApplicationContextAware or, if the listener is a bean, by using
@Autowired.

Web Environment
A SpringApplication attempts to create the right type of ApplicationContext on
your behalf. The algorithm used to determine a WebApplicationType is fairly simple:

● If Spring MVC is present, an


AnnotationConfigServletWebServerApplicationContext is used
● If Spring MVC is not present and Spring WebFlux is present, an
AnnotationConfigReactiveWebServerApplicationContext is used
● Otherwise, AnnotationConfigApplicationContext is used

This means that if you are using Spring MVC and the new WebClient from Spring
WebFlux in the same application, Spring MVC will be used by default. You can override that
easily by calling setWebApplicationType(WebApplicationType).

It is also possible to take complete control of the ApplicationContext type that is used
by calling setApplicationContextClass(…).

It is often desirable to call


setWebApplicationType(WebApplicationType.NONE) when
using SpringApplication within a JUnit test.

Accessing Application Arguments


If you need to access the application arguments that were passed to
SpringApplication.run(…), you can inject
aorg.springframework.boot.ApplicationArguments bean. The
ApplicationArguments interface provides access to both the raw String[]
arguments as well as parsed option and non-option arguments, as shown in the
following example:
import org.springframework.boot.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

@Component
public class MyBean {

@Autowired
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
// if run with "--debug logfile.txt" debug=true,
files=["logfile.txt"]
}

Spring Boot also registers a


CommandLinePropertySource with the Spring
Environment. This lets you also inject single application
arguments by using the @Value annotation.

Using the ApplicationRunner or CommandLineRunner


If you need to run some specific code once the SpringApplication has started, you
can implement the ApplicationRunner or CommandLineRunner interfaces. Both
interfaces work in the same way and offer a single run method, which is called just before
SpringApplication.run(…) completes.

The CommandLineRunner interfaces provides access to application arguments as a


simple string array, whereas the ApplicationRunner uses the
ApplicationArguments interface discussed earlier. The following example shows a
CommandLineRunner with a run method:
import org.springframework.boot.*;
import org.springframework.stereotype.*;

@Component
public class MyBean implements CommandLineRunner {

public void run(String... args) {


// Do something...
}

If several CommandLineRunner or ApplicationRunner beans are defined that must


be called in a specific order, you can additionally implement
theorg.springframework.core.Ordered interface or use the
org.springframework.core.annotation.Order annotation.

Admin Features
It is possible to enable admin-related features for the application by specifying the
spring.application.admin.enabled property. This exposes
theSpringApplicationAdminMXBean on the platform MBeanServer. You could
use this feature to administer your Spring Boot application remotely. This feature could also
be useful for any service wrapper implementation.

If you want to know on which HTTP port the application is


running, get the property with a key of local.server.port.

Caution

Take care when enabling this feature, as the MBean exposes a


method to shutdown the application.

Externalized Configuration
Spring Boot lets you externalize your configuration so that you can work with the same
application code in different environments. You can use properties files, YAML files,
environment variables, and command-line arguments to externalize configuration. Property
values can be injected directly into your beans by using the @Valueannotation, accessed
through Spring’s Environment abstraction, or be bound to structured objects through
@ConfigurationProperties.

Spring Boot uses a very particular PropertySource order that is designed to allow
sensible overriding of values. Properties are considered in the following order:

1. Devtools global settings properties on your home directory (~/.spring-boot-


devtools.properties when devtools is active).
2. @TestPropertySource annotations on your tests.
3. properties attribute on your tests. Available on @SpringBootTest and the
test annotations for testing a particular slice of your application.
4. Command line arguments.
5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an
environment variable or system property).
6. ServletConfig init parameters.
7. ServletContext init parameters.
8. JNDI attributes from java:comp/env.
9. Java System properties (System.getProperties()).
10. OS environment variables.
11. A RandomValuePropertySource that has properties only in random.*.
12. Profile-specific application properties outside of your packaged jar (application-
{profile}.properties and YAML variants).
13. Profile-specific application properties packaged inside your jar (application-
{profile}.properties and YAML variants).
14. Application properties outside of your packaged jar (application.properties
and YAML variants).
15. Application properties packaged inside your jar (application.properties and
YAML variants).
16. @PropertySource annotations on your @Configuration classes.
17. Default properties (specified by setting
SpringApplication.setDefaultProperties).

To provide a concrete example, suppose you develop a @Component that uses a name
property, as shown in the following example:

import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;

@Component
public class MyBean {

@Value("${name}")
private String name;

// ...
}

On your application classpath (for example, inside your jar) you can have an
application.properties file that provides a sensible default property value for
name. When running in a new environment, an application.properties file can be
provided outside of your jar that overrides the name. For one-off testing, you can launch with
a specific command line switch (for example, java -jar app.jar
--name="Spring").

The SPRING_APPLICATION_JSON properties can be supplied on the


command line with an environment variable. For example, you could use the
following line in a UN*X shell:

$ SPRING_APPLICATION_JSON='{"acme":{"name":"test"}}' java
-jar myapp.jar

In the preceding example, you end up with acme.name=test in the Spring

Environment. You can also supply the JSON as


spring.application.jsonin a System property, as shown in the following
example:

$ java -Dspring.application.json='{"name":"test"}' -jar


myapp.jar

You can also supply the JSON by using a command line argument, as shown in
the following example:

$ java -jar myapp.jar


--spring.application.json='{"name":"test"}'

You can also supply the JSON as a JNDI variable, as follows:


java:comp/env/spring.application.json.

Configuring Random Values


The RandomValuePropertySource is useful for injecting random values (for example,
into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the
following example:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

The random.int* syntax is OPEN value (,max) CLOSE where the OPEN,CLOSE
are any character and value,max are integers. If max is provided, then value is the
minimum value and max is the maximum value (exclusive).

Accessing Command Line Properties


By default, SpringApplication converts any command line option arguments (that is,
arguments starting with --, such as --server.port=9000) to a propertyand adds
them to the Spring Environment. As mentioned previously, command line properties
always take precedence over other property sources.

If you do not want command line properties to be added to the Environment, you can
disable them by using
SpringApplication.setAddCommandLineProperties(false).
Application Property Files
SpringApplication loads properties from application.properties files in the
following locations and adds them to the Spring Environment:

1. A /config subdirectory of the current directory


2. The current directory
3. A classpath /config package
4. The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override
those defined in lower locations).

You can also use YAML ('.yml') files as an alternative to


'.properties'.

If you do not like application.properties as the configuration file name, you can
switch to another file name by specifying a spring.config.name environment property.
You can also refer to an explicit location by using the spring.config.location
environment property (which is a comma-separated list of directory locations or file paths).
The following example shows how to specify a different file name:

$ java -jar myproject.jar --spring.config.name=myproject

The following example shows how to specify two locations:

$ java -jar myproject.jar


--spring.config.location=classpath:/default.properties,classpath:/overrid
e.properties

spring.config.name and spring.config.location


are used very early to determine which files have to be loaded, so
they must be defined as an environment property (typically an OS
environment variable, a system property, or a command-line
argument).

Profile-specific Properties
In addition to application.properties files, profile-specific properties can also be
defined by using the following naming convention: application-
{profile}.properties. The Environment has a set of default profiles (by default,
[default]) that are used if no active profiles are set. In other words, if no profiles are
explicitly activated, then properties from application-default.properties are
loaded.

Profile-specific properties are loaded from the same locations as standard


application.properties, with profile-specific files always overriding the non-specific
ones, whether or not the profile-specific files are inside or outside your packaged jar.

If several profiles are specified, a last-wins strategy applies. For example, profiles specified
by the spring.profiles.active property are added after those configured through
the SpringApplication API and therefore take precedence.

Placeholders in Properties
The values in application.properties are filtered through the existing
Environment when they are used, so you can refer back to previously defined values (for
example, from System properties).

app.name=MyApp
app.description=${app.name} is a Spring Boot application

You can also use this technique to create “short” variants of


existing Spring Boot properties. See the Section 76.4, “Use
‘Short’ Command Line Arguments”how-to for details.

Using YAML Instead of Properties


YAML is a superset of JSON and, as such, is a convenient format for specifying hierarchical
configuration data. The SpringApplication class automatically supports YAML as an
alternative to properties whenever you have the SnakeYAML library on your classpath.
If you use “Starters”, SnakeYAML is automatically provided by
spring-boot-starter.

Loading YAML
Spring Framework provides two convenient classes that can be used to load YAML
documents. The YamlPropertiesFactoryBean loads YAML as Properties and
the YamlMapFactoryBean loads YAML as a Map.

For example, consider the following YAML document:

environments:
dev:
url: http://dev.example.com
name: Developer Setup
prod:
url: http://another.example.com
name: My Cool App

The preceding example would be transformed into the following properties:

environments.dev.url=http://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=http://another.example.com
environments.prod.name=My Cool App

YAML lists are represented as property keys with [index] dereferencers. For example,
consider the following YAML:

my:
servers:
- dev.example.com
- another.example.com

The preceding example would be transformed into these properties:

my.servers[0]=dev.example.com
my.servers[1]=another.example.com
To bind to properties like that by using Spring Boot’s Binder utilities (which is what
@ConfigurationProperties does), you need to have a property in the target bean of
type java.util.List (or Set) and you either need to provide a setter or initialize it with
a mutable value. For example, the following example binds to the properties shown
previously:

@ConfigurationProperties(prefix="my")
public class Config {

private List<String> servers = new ArrayList<String>();

public List<String> getServers() {


return this.servers;
}
}

Exposing YAML as Properties in the Spring Environment


The YamlPropertySourceLoader class can be used to expose YAML as a
PropertySource in the Spring Environment. Doing so lets you use the
@Valueannotation with placeholders syntax to access YAML properties.

YAML Shortcomings
YAML files cannot be loaded by using the @PropertySource annotation. So, in the case
that you need to load values that way, you need to use a properties file.

Type-safe Configuration Properties


Using 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 lets strongly typed beans govern and validate the configuration of your
application, as shown in the following example:

package com.example;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import
org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("acme")
public class AcmeProperties {

private boolean enabled;

private InetAddress remoteAddress;

private final Security security = new Security();

public boolean isEnabled() { ... }

public void setEnabled(boolean enabled) { ... }

public InetAddress getRemoteAddress() { ... }

public void setRemoteAddress(InetAddress remoteAddress) { ... }

public Security getSecurity() { ... }

public static class Security {

private String username;

private String password;

private List<String> roles = new


ArrayList<>(Collections.singleton("USER"));

public String getUsername() { ... }

public void setUsername(String username) { ... }

public String getPassword() { ... }

public void setPassword(String password) { ... }


public List<String> getRoles() { ... }

public void setRoles(List<String> roles) { ... }

}
}

The preceding POJO defines the following properties:

● acme.enabled, with a value of false by default.


● acme.remote-address, with a type that can be coerced from String.
● acme.security.username, with a nested "security" object whose name is
determined by the name of the property. In particular, the return type is not used at
all there and could have been SecurityProperties.
● acme.security.password.
● acme.security.roles, with a collection of String.
Getters and setters are usually mandatory, since binding is
through standard Java Beans property descriptors, just like in
Spring MVC. A setter may be omitted in the following cases:

● Maps, as long as they are initialized, need a getter but


not necessarily a setter, since they can be mutated by
the binder.
● Collections and arrays can be accessed either through
an index (typically with YAML) or by using a single
comma-separated value (properties). In the latter case, a
setter is mandatory. We recommend to always add a
setter for such types. If you initialize a collection, make
sure it is not immutable (as in the preceding example).
● If nested POJO properties are initialized (like the
Security field in the preceding example), a setter is
not required. If you want the binder to create the
instance on the fly by using its default constructor, you
need a setter.

Some people use Project Lombok to add getters and setters


automatically. Make sure that Lombok does not generate any
particular constructor for such a type, as it is used automatically
by the container to instantiate the object.

Finally, only standard Java Bean properties are considered and


binding on static properties is not supported.

Even if the preceding configuration creates a regular bean for AcmeProperties, we


recommend that @ConfigurationProperties only deal with the environment and, in
particular, does not inject other beans from the context. Having said that, the
@EnableConfigurationProperties annotation is also automatically applied to your
project so that any existing bean annotated with @ConfigurationProperties is
configured from the Environment. You could shortcut MyConfiguration by making
sure AcmeProperties is already a bean, as shown in the following example:

@Component
@ConfigurationProperties(prefix="acme")
public class AcmeProperties {

// ... see the preceding example

This style of configuration works particularly well with the SpringApplication external
YAML configuration, as shown in the following example:

# application.yml

acme:
remote-address: 192.168.1.1
security:
username: admin
roles:
- USER
- ADMIN

# additional configuration as required

To work with @ConfigurationProperties beans, you can inject them in the same
way as any other bean, as shown in the following example:

@Service
public class MyService {

private final AcmeProperties properties;

@Autowired
public MyService(AcmeProperties properties) {
this.properties = properties;
}

//...

@PostConstruct
public void openConnection() {
Server server = new Server(this.properties.getRemoteAddress());
// ...
}

Third-party Configuration
As well as using @ConfigurationProperties to annotate a class, you can also use it
on public @Bean methods. Doing so can be particularly useful when you want to bind
properties to third-party components that are outside of your control.

To configure a bean from the Environment properties, add


@ConfigurationProperties to its bean registration, as shown in the following
example:

@ConfigurationProperties(prefix = "another")
@Bean
public AnotherComponent anotherComponent() {
...
}

Any property defined with the another prefix is mapped onto that AnotherComponent
bean in manner similar to the preceding AcmeProperties example.

Relaxed Binding
Spring Boot uses some relaxed rules for binding Environment properties to
@ConfigurationProperties beans, so there does not need to be an exact match
between the Environment property name and the bean property name. Common
examples where this is useful include dash-separated environment properties (for example,
context-path binds to contextPath), and capitalized environment properties (for
example, PORT binds to port).

For example, consider the following @ConfigurationProperties class:

@ConfigurationProperties(prefix="acme.my-project.person")
public class OwnerProperties {

private String firstName;

public String getFirstName() {


return this.firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

In the preceding example, the following properties names can all be used:

Table 24.1. relaxed binding

Property Note
acme.my- Kebab case, which is recommended for use in
project.person. .properties and .yml files.
first-name

acme.myProject. Standard camel case syntax.


person.firstNam
e

acme.my_project Underscore notation, which is an alternative format for


.person.first_n use in .properties and .yml files.

ame

ACME_MYPROJECT_ Upper case format, which is recommended when using


PERSON_FIRSTNAM system environment variables.

When binding to Map properties, if the key contains anything other than lowercase alpha-
numeric characters or -, you need to use the bracket notation so that the original value is
preserved. If the key is not surrounded by [], any characters that are not alpha-numeric or
- are removed. For example, consider binding the following properties to a Map:

acme:
map:
"[/key1]": value1
"[/key2]": value2
/key3: value3

The properties above will bind to a Map with /key1, /key2 and key3 as the keys in the
map.

@ConfigurationProperties Validation
Spring Boot attempts to validate @ConfigurationProperties classes whenever they
are annotated with Spring’s @Validated annotation. You can use JSR-303
javax.validation constraint annotations directly on your configuration class. To do so,
ensure that a compliant JSR-303 implementation is on your classpath and then add
constraint annotations to your fields, as shown in the following example:
@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

@NotNull
private InetAddress remoteAddress;

// ... getters and setters

You can also trigger validation by annotating the @Bean


method that creates the configuration properties with
@Validated.

You can also add a custom Spring Validator by creating a bean definition called
configurationPropertiesValidator. The @Bean method should be declared static. The
configuration properties validator is created very early in the application’s lifecycle, and declaring the
@Bean method as static lets the bean be created without having to instantiate the @Configuration
class. Doing so avoids any problems that may be caused by early instantiation. There is a property
validation samplethat shows how to set things up.

@ConfigurationProperties vs. @Value


The @Value annotation is a core container feature, and it does not provide the same
features as type-safe configuration properties. The following table summarizes the features
that are supported by @ConfigurationProperties and @Value:

Feature @ConfigurationProperties @Value

Relaxed binding Yes No

Meta-data support Yes No

SpEL evaluation No Yes


If you define a set of configuration keys for your own components, we recommend you group
them in a POJO annotated with @ConfigurationProperties. You should also be
aware that, since @Value does not support relaxed binding, it is not a good candidate if you
need to provide the value by using environment variables.

Finally, while you can write a SpEL expression in @Value, such expressions are not
processed from application property files.

Profiles
Spring Profiles provide a way to segregate parts of your application configuration and make
it be available only in certain environments. Any @Component or @Configuration can
be marked with @Profile to limit when it is loaded, as shown in the following example:

@Configuration
@Profile("production")
public class ProductionConfiguration {

// ...

You can use a spring.profiles.active Environment property to specify which


profiles are active. You can specify the property in any of the ways described earlier in this
chapter. For example, you could include it in your application.properties, as
shown in the following example:

spring.profiles.active=dev,hsqldb

You could also specify it on the command line by using the following switch:
--spring.profiles.active=dev,hsqldb.

Programmatically Setting Profiles


You can programmatically set active profiles by calling
SpringApplication.setAdditionalProfiles(…) before your application runs.
It is also possible to activate profiles by using Spring’s ConfigurableEnvironment
interface.

Profile-specific Configuration Files


Profile-specific variants of both application.properties (or application.yml)
and files referenced through @ConfigurationProperties are considered as files and
loaded. See "Section 24.4, “Profile-specific Properties”" for details.
Logging
Spring Boot uses Commons Logging for all internal logging but leaves the underlying log
implementation open. Default configurations are provided for Java Util Logging, Log4J2, and
Logback. In each case, loggers are pre-configured to use console output with optional file
output also available.

By default, if you use the “Starters”, Logback is used for logging. Appropriate Logback
routing is also included to ensure that dependent libraries that use Java Util Logging,
Commons Logging, Log4J, or SLF4J all work correctly.

There are a lot of logging frameworks available for Java. Do not


worry if the above list seems confusing. Generally, you do not
need to change your logging dependencies and the Spring Boot
defaults work just fine.

Log Format
The default log output from Spring Boot resembles the following example:

2014-03-05 10:57:51.112 INFO 45469 --- [ main]


org.apache.catalina.core.StandardEngine : Starting Servlet Engine:
Apache Tomcat/7.0.52
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1]
o.s.web.context.ContextLoader : Root WebApplicationContext:
initialization completed in 1358 ms
2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1]
o.s.b.c.e.ServletRegistrationBean : Mapping servlet:
'dispatcherServlet' to [/]
2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1]
o.s.b.c.embedded.FilterRegistrationBean : Mapping filter:
'hiddenHttpMethodFilter' to: [/*]
The following items are output:

● Date and Time: Millisecond precision and easily sortable.


● Log Level: ERROR, WARN, INFO, DEBUG, or TRACE.
● Process ID.
● A --- separator to distinguish the start of actual log messages.
● Thread name: Enclosed in square brackets (may be truncated for console output).
● Logger name: This is usually the source class name (often abbreviated).
● The log message.

Logback does not have a FATAL level. It is mapped to ERROR.

Console Output
The default log configuration echoes messages to the console as they are written. By
default, ERROR-level, WARN-level, and INFO-level messages are logged. You can also
enable a “debug” mode by starting your application with a --debug flag.

$ java -jar myapp.jar --debug

You can also specify debug=true in your

application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container,
Hibernate, and Spring Boot) are configured to output more information. Enabling the debug
mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace
flag (or trace=true in your application.properties). Doing so enables trace
logging for a selection of core loggers (embedded container, Hibernate schema generation,
and the whole Spring portfolio).

File Output
By default, Spring Boot logs only to the console and does not write log files. If you want to
write log files in addition to the console output, you need to set alogging.file or
logging.path property (for example, in your application.properties).
The following table shows how the logging.* properties can be used together:

Table 26.1. Logging properties

logging.file
logging.path
Example Description

(non (non Console only logging.


e) e)

Spe (non m Writes to the specified log file. Names can be an exact
cific e) y location or relative to the current directory.
file .
l
o
g

(non Spe / Writes spring.log to the specified directory. Names


e) cific v can be an exact location or relative to the current
dire a directory.
ctor r
y
/
l
o
g

Log files rotate when they reach 10 MB and, as with console output, ERROR-level, WARN-
level, and INFO-level messages are logged by default. Size limits can be changed using the
logging.file.max-size property. Previously rotated files are archived indefinitely
unless the logging.file.max-history property has been set.

Log Levels
All the supported logging systems can have the logger levels set in the Spring
Environment (for example, in application.properties) by
usinglogging.level.<logger-name>=<level> where level is one of TRACE,
DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The root logger can be configured by
using logging.level.root.

The following example shows potential logging settings in application.properties:

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

Custom Log Configuration


The various logging systems can be activated by including the appropriate libraries on the
classpath and can be further customized by providing a suitable configuration file in the root
of the classpath or in a location specified by the following Spring Environment property:
logging.config.

You can force Spring Boot to use a particular logging system by using the
org.springframework.boot.logging.LoggingSystem system property. The
value should be the fully qualified class name of a LoggingSystem implementation. You
can also disable Spring Boot’s logging configuration entirely by using a value of none.

Since logging is initialized before the ApplicationContext


is created, it is not possible to control logging from
@PropertySources in Spring @Configuration files.
The only way to change the logging system or disable it entirely
is via System properties.

Depending on your logging system, the following files are loaded:

Logging System Customization

Logback logback-spring.xml, logback-spring.groovy,


logback.xml, or logback.groovy

Log4j2 log4j2-spring.xml or log4j2.xml

JDK (Java Util logging.properties


Logging)

When possible, we recommend that you use the -spring

variants for your logging configuration (for example, logback-

spring.xml rather than logback.xml). If you use


standard configuration locations, Spring cannot completely
control log initialization.

There are known classloading issues with Java Util Logging that
cause problems when running from an 'executable jar'. We
recommend that you avoid it when running from an 'executable
jar' if at all possible.

To help with the customization, some other properties are transferred from the Spring
Environment to System properties, as described in the following table:

Spring Environment System Property Comments


logging.except LOG_EXCEPTIO The conversion word used when logging
ion- N_CONVERSION exceptions.

conversion- _WORD
word

logging.file LOG_FILE If defined, it is used in the default log


configuration.

logging.file.m LOG_FILE_MAX Maximum log file size (if LOG_FILE


ax-size _SIZE enabled). (Only supported with the
default Logback setup.)

logging.file.m LOG_FILE_MAX Maximum number of archive log files to


ax-history _HISTORY keep (if LOG_FILE enabled). (Only
supported with the default Logback
setup.)

logging.path LOG_PATH If defined, it is used in the default log


configuration.

logging.patter CONSOLE_LOG_ The log pattern to use on the console


n.console PATTERN (stdout). (Only supported with the default
Logback setup.)

logging.patter LOG_DATEFORM Appender pattern for log date format.


n.dateformat AT_PATTERN (Only supported with the default
Logback setup.)

logging.patter FILE_LOG_PAT The log pattern to use in a file (if


n.file TERN LOG_FILE is enabled). (Only
supported with the default Logback
setup.)

logging.patter LOG_LEVEL_PA
n.level TTERN
The format to use when rendering the
log level (default %5p). (Only supported
with the default Logback setup.)

PID PID The current process ID (discovered if


possible and when not already defined
as an OS environment variable).

All the supported logging systems can consult System properties when parsing their
configuration files. See the default configurations in spring-boot.jar for examples:

● Logback
● Log4j 2
● Java Util logging

If you want to use a placeholder in a logging property, you


should use Spring Boot’s syntax and not the syntax of the
underlying framework. Notably, if you use Logback, you should
use : as the delimiter between a property name and its default

value and not use :-.

You can add MDC and other ad-hoc content to log lines by overriding only the
LOG_LEVEL_PATTERN (or logging.pattern.level with Logback). For
example, if you use logging.pattern.level=user:%X{user} %5p, then
the default log format contains an MDC entry for "user", if it exists, as shown in the
following example.

2015-09-30 12:30:04.031 user:someone INFO 22174 --- [ nio-


8080-exec-0] demo.Controller
Handling authenticated request

JSON
Spring Boot provides integration with three JSON mapping libraries:

● Gson
● Jackson
● JSON-B

Jackson is the preferred and default library.

Jackson
Auto-configuration for Jackson is provided and Jackson is part of spring-boot-
starter-json. When Jackson is on the classpath an ObjectMapper bean is
automatically configured. Several configuration properties are provided for customizing the
configuration of the ObjectMapper.

Gson
Auto-configuration for Gson is provided. When Gson is on the classpath a Gson bean is
automatically configured. Several spring.gson.* configuration properties are provided
for customizing the configuration. To take more control, one or more
GsonBuilderCustomizer beans can be used.

JSON-B
Auto-configuration for JSON-B is provided. When the JSON-B API and an implementation
are on the classpath a Jsonb bean will be automatically configured. The preferred JSON-B
implementation is Apache Johnzon for which dependency management is provided.

The “Spring Web MVC Framework”


The Spring Web MVC framework (often referred to as simply “Spring MVC”) is a rich “model
view controller” web framework. Spring MVC lets you create special @Controller or
@RestController beans to handle incoming HTTP requests. Methods in your controller
are mapped to HTTP by using @RequestMappingannotations.

The following code shows a typical @RestController that serves JSON data:

@RestController
@RequestMapping(value="/users")
public class MyRestController {

@RequestMapping(value="/{user}", method=RequestMethod.GET)
public User getUser(@PathVariable Long user) {
// ...
}

@RequestMapping(value="/{user}/customers", method=RequestMethod.GET)
List<Customer> getUserCustomers(@PathVariable Long user) {
// ...
}

@RequestMapping(value="/{user}", method=RequestMethod.DELETE)
public User deleteUser(@PathVariable Long user) {
// ...
}

Spring MVC is part of the core Spring Framework, and detailed information is available in the
reference documentation. There are also several guides that cover Spring MVC available at
spring.io/guides.

Spring MVC Auto-configuration


Spring Boot provides auto-configuration for Spring MVC that works well with most
applications.

The auto-configuration adds the following features on top of Spring’s defaults:

● Inclusion of ContentNegotiatingViewResolver and


BeanNameViewResolver beans.
● Support for serving static resources, including support for WebJars (covered later in
this document)).
● Automatic registration of Converter, GenericConverter, and Formatter
beans.
● Support for HttpMessageConverters (covered later in this document).
● Automatic registration of MessageCodesResolver (covered later in this
document).
● Static index.html support.
● Custom Favicon support (covered later in this document).
● Automatic use of a ConfigurableWebBindingInitializer bean (covered
later in this document).

If you want to keep Spring Boot MVC features and you want to add additional MVC
configuration (interceptors, formatters, view controllers, and other features), you can add
your own @Configuration class of type WebMvcConfigurer but without
@EnableWebMvc. If you wish to provide custom instances of
RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or
ExceptionHandlerExceptionResolver, you can declare a
WebMvcRegistrationsAdapter instance to provide such components.

If you want to take complete control of Spring MVC, you can add your own
@Configuration annotated with @EnableWebMvc.

HttpMessageConverters
Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and
responses. Sensible defaults are included out of the box. For example, objects can be
automatically converted to JSON (by using the Jackson library) or XML (by using the
Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not
available). By default, strings are encoded in UTF-8.

If you need to add or customize converters, you can use Spring Boot’s
HttpMessageConverters class, as shown in the following listing:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;

@Configuration
public class MyConfiguration {

@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
}

}
Any HttpMessageConverter bean that is present in the context is added to the list of
converters. You can also override default converters in the same way.

Custom JSON Serializers and Deserializers


If you use Jackson to serialize and deserialize JSON data, you might want to write your own
JsonSerializer and JsonDeserializer classes. Custom serializers are usually
registered with Jackson through a module, but Spring Boot provides an alternative
@JsonComponent annotation that makes it easier to directly register Spring Beans.

You can use the @JsonComponent annotation directly on JsonSerializer or


JsonDeserializer implementations. You can also use it on classes that contain
serializers/deserializers as inner classes, as shown in the following example:

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;

@JsonComponent
public class Example {

public static class Serializer extends JsonSerializer<SomeObject> {


// ...
}

public static class Deserializer extends JsonDeserializer<SomeObject>


{
// ...
}

All @JsonComponent beans in the ApplicationContext are automatically registered


with Jackson. Because @JsonComponent is meta-annotated with @Component, the
usual component-scanning rules apply.

Spring Boot also provides JsonObjectSerializer and


JsonObjectDeserializer base classes that provide useful alternatives to the
standard Jackson versions when serializing objects. See JsonObjectSerializer and
JsonObjectDeserializer in the Javadoc for details.

MessageCodesResolver
Spring MVC has a strategy for generating error codes for rendering error messages from
binding errors: MessageCodesResolver. If you set thespring.mvc.message-
codes-resolver.format property PREFIX_ERROR_CODE or
POSTFIX_ERROR_CODE, Spring Boot creates one for you (see the enumeration
inDefaultMessageCodesResolver.Format).

Static Content
By default, Spring Boot serves static content from a directory called /static (or /public
or /resources or /META-INF/resources) in the classpath or from the root of the
ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so
that you can modify that behavior by adding your own WebMvcConfigurerand overriding
the addResourceHandlers method.

In a stand-alone 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 does not happen (unless you modify the default MVC
configuration), because Spring can always handle requests through the
DispatcherServlet.

By default, resources are mapped on /**, but you can tune that with the
spring.mvc.static-path-pattern property. For instance, relocating all resources
to/resources/** can be achieved as follows:

spring.mvc.static-path-pattern=/resources/**

You can also customize the static resource locations by using the
spring.resources.static-locations property (replacing the default values with
a list of directory locations). The root Servlet context path, "/", is automatically added as a
location as well.

Welcome Page
Spring Boot supports both static and templated welcome pages. It first looks for an
index.html file in the configured static content locations. If one is not found, it then looks
for an index template. If either is found, it is automatically used as the welcome page of the
application.

Custom Favicon
Spring Boot looks for a favicon.ico in the configured static content locations and the
root of the classpath (in that order). If such a file is present, it is automatically used as the
favicon of the application.

Path Matching and Content Negotiation


Spring MVC can map incoming HTTP requests to handlers by looking at the request path
and matching it to the mappings defined in your application (for example, @GetMapping
annotations on Controller methods).

Spring Boot chooses to disable suffix pattern matching by default, which means that
requests like "GET /projects/spring-boot.json" won’t be matched
to@GetMapping("/projects/spring-boot") mappings. This is considered as a
best practice for Spring MVC applications. This feature was mainly useful in the past for
HTTP clients which did not send proper "Accept" request headers; we needed to make sure
to send the correct Content Type to the client. Nowadays, Content Negotiation is much more
reliable.

There are other ways to deal with HTTP clients that don’t consistently send proper "Accept"
request headers. Instead of using suffix matching, we can use a query parameter to ensure
that requests like "GET /projects/spring-boot?format=json" will be mapped
to @GetMapping("/projects/spring-boot"):

spring.mvc.contentnegotiation.favor-parameter=true

# We can change the parameter name, which is "format" by default:


# spring.mvc.contentnegotiation.parameter-name=myparam

# We can also register additional file extensions/media types with:


spring.mvc.contentnegotiation.media-types.markdown=text/markdown

Template Engines
As well as REST web services, you can also use Spring MVC to serve dynamic HTML
content. Spring MVC supports a variety of templating technologies, including Thymeleaf,
FreeMarker, and JSPs. Also, many other templating engines include their own Spring MVC
integrations.

Spring Boot includes auto-configuration support for the following templating engines:

● FreeMarker
● Groovy
● Thymeleaf
● Mustache

If possible, JSPs should be avoided. There are several known


limitations when using them with embedded servlet containers.
When you use one of these templating engines with the default configuration, your templates
are picked up automatically from src/main/resources/templates.

Depending on how you run your application, IntelliJ IDEA orders


the classpath differently. Running your application in the IDE
from its main method results in a different ordering than when
you run your application by using Maven or Gradle or from its
packaged jar. This can cause Spring Boot to fail to find the
templates on the classpath. If you have this problem, you can
reorder the classpath in the IDE to place the module’s classes
and resources first. Alternatively, you can configure the
template prefix to search every templates directory on the

classpath, as follows: classpath*:/templates/.

Error Handling
By default, Spring Boot provides an /error mapping that handles all errors in a sensible
way, and it is registered as a “global” error page in the servlet container. For machine clients,
it produces a JSON response with details of the error, the HTTP status, and the exception
message. For browser clients, there is a “whitelabel” error view that renders the same data
in HTML format (to customize it, add a View that resolves to error). To replace the default
behavior completely, you can implementErrorController and register a bean definition
of that type or add a bean of type ErrorAttributes to use the existing mechanism but
replace the contents.
The BasicErrorController can be used as a base class

for a custom ErrorController. This is particularly useful if


you want to add a handler for a new content type (the default is
to handle text/html specifically and provide a fallback for
everything else). To do so, extend
BasicErrorController, add a public method with a
@RequestMapping that has a produces attribute, and
create a bean of your new type.

You can also define a class annotated with @ControllerAdvice to customize the JSON
document to return for a particular controller and/or exception type, as shown in the following
example:

@ControllerAdvice(basePackageClasses = AcmeController.class)
public class AcmeControllerAdvice extends ResponseEntityExceptionHandler
{

@ExceptionHandler(YourException.class)
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest
request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new CustomErrorType(status.value(),
ex.getMessage()), status);
}

private HttpStatus getStatus(HttpServletRequest request) {


Integer statusCode = (Integer)
request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}

In the preceding example, if YourException is thrown by a controller defined in the same


package as AcmeController, a JSON representation of the CustomErrorType
POJO is used instead of the ErrorAttributes representation.

Custom Error Pages


If you want to display a custom HTML error page for a given status code, you can add a file
to an /error folder. Error pages can either be static HTML (that is, added under any of the
static resource folders) or be built by using templates. The name of the file should be the
exact status code or a series mask.

For example, to map 404 to a static HTML file, your folder structure would be as follows:

src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>

To map all 5xx errors by using a FreeMarker template, your folder structure would be as
follows:

src/
+- main/
+- java/
| + <source code>
+- resources/
+- templates/
+- error/
| +- 5xx.ftl
+- <other templates>

For more complex mappings, you can also add beans that implement the
ErrorViewResolver interface, as shown in the following example:

public class MyErrorViewResolver implements ErrorViewResolver {

@Override
public ModelAndView resolveErrorView(HttpServletRequest request,
HttpStatus status, Map<String, Object> model) {
// Use the request or status to optionally return a ModelAndView
return ...
}

You can also use regular Spring MVC features such as @ExceptionHandler methods
and @ControllerAdvice. The ErrorController then picks up any unhandled
exceptions.

Spring HATEOAS
If you develop a RESTful API that makes use of hypermedia, Spring Boot provides auto-
configuration for Spring HATEOAS that works well with most applications. The auto-
configuration replaces the need to use @EnableHypermediaSupport and registers a
number of beans to ease building hypermedia-based applications, including
aLinkDiscoverers (for client side support) and an ObjectMapper configured to
correctly marshal responses into the desired representation. The ObjectMapper is
customized by setting the various spring.jackson.* properties or, if one exists, by a
Jackson2ObjectMapperBuilder bean.

You can take control of Spring HATEOAS’s configuration by using


@EnableHypermediaSupport. Note that doing so disables the ObjectMapper
customization described earlier.

CORS Support
Cross-origin resource sharing (CORS) is a W3C specification implemented by most
browsers that lets you specify in a flexible way what kind of cross-domain requests are
authorized, instead of using some less secure and less powerful approaches such as
IFRAME or JSONP.

As of version 4.2, Spring MVC supports CORS. Using controller method CORS configuration
with @CrossOrigin annotations in your Spring Boot application does not require any
specific configuration. Global CORS configuration can be defined by registering a
WebMvcConfigurer bean with a customizedaddCorsMappings(CorsRegistry)
method, as shown in the following example:

@Configuration
public class MyConfiguration {

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}

Embedded Servlet Container Support


Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most
developers use the appropriate “Starter” to obtain a fully configured instance. By default, the
embedded server listens for HTTP requests on port 8080.

If you choose to use Tomcat on CentOS, be aware that, by


default, a temporary directory is used to store compiled JSPs,
file uploads, and so on. This directory may be deleted by
tmpwatch while your application is running, leading to failures.
To avoid this behavior, you may want to customize your
tmpwatch configuration such that tomcat.* directories are
not deleted or configure server.tomcat.basedir such
that embedded Tomcat uses a different location.

Servlets, Filters, and listeners


When using an embedded servlet container, you can register servlets, filters, and all the
listeners (such as HttpSessionListener) from the Servlet spec, either by using Spring
beans or by scanning for Servlet components.

Registering Servlets, Filters, and Listeners as Spring Beans


Any Servlet, Filter, or servlet *Listener instance that is a Spring bean is
registered with the embedded container. This can be particularly convenient if you want to
refer to a value from your application.properties during configuration.

By default, if the context contains only a single Servlet, it is mapped to /. In the case of
multiple servlet beans, the bean name is used as a path prefix. Filters map to/*.

If convention-based mapping is not flexible enough, you can use the


ServletRegistrationBean, FilterRegistrationBean,
andServletListenerRegistrationBean classes for complete control.

Servlet Context Initialization


Embedded servlet containers do not directly execute the Servlet 3.0+
javax.servlet.ServletContainerInitializer interface or
Spring’sorg.springframework.web.WebApplicationInitializer interface.
This is an intentional design decision intended to reduce the risk that third party libraries
designed to run inside a war may break Spring Boot applications.

If you need to perform servlet context initialization in a Spring Boot application, you should
register a bean that implements
theorg.springframework.boot.web.servlet.ServletContextInitializ
er interface. The single onStartup method provides access to the ServletContext
and, if necessary, can easily be used as an adapter to an existing
WebApplicationInitializer.

Scanning for Servlets, Filters, and listeners


When using an embedded container, automatic registration of classes annotated with
@WebServlet, @WebFilter, and @WebListener can be enabled by
using@ServletComponentScan.
@ServletComponentScan has no effect in a standalone
container, where the container’s built-in discovery mechanisms
are used instead.

The ServletWebServerApplicationContext
Under the hood, Spring Boot uses a different type of ApplicationContext for
embedded servlet container support. The ServletWebServerApplicationContext
is a special type of WebApplicationContext that bootstraps itself by searching for a
single ServletWebServerFactory bean. Usually a
TomcatServletWebServerFactory, JettyServletWebServerFactory, or
UndertowServletWebServerFactory has been auto-configured.

You usually do not need to be aware of these implementation classes. Most


applications are auto-configured, and the appropriate
ApplicationContextand ServletWebServerFactory are created
on your behalf.

Customizing Embedded Servlet Containers


Common servlet container settings can be configured by using Spring Environment
properties. Usually, you would define the properties in your application.properties
file.

Common server settings include:

● Network settings: Listen port for incoming HTTP requests (server.port),


interface address to bind to server.address, and so on.
● Session settings: Whether the session is persistent
(server.servlet.session.persistence), session timeout
(server.servlet.session.timeout), location of session data
(server.servlet.session.store-dir), and session-cookie configuration
(server.servlet.session.cookie.*).
● Error management: Location of the error page (server.error.path) and so on.
● SSL
● HTTP compression

Spring Boot tries as much as possible to expose common settings, but this is not always
possible. For those cases, dedicated namespaces offer server-specific customizations (see
server.tomcat and server.undertow). For instance, access logs can be configured
with specific features of the embedded servlet container.

See the ServerProperties class for a complete list.

Programmatic Customization
If you need to programmatically configure your embedded servlet container, you can register
a Spring bean that implements the WebServerFactoryCustomizerinterface.
WebServerFactoryCustomizer provides access to the
ConfigurableServletWebServerFactory, which includes numerous
customization setter methods. The following example shows programmatically setting the
port:

import
org.springframework.boot.web.server.WebServerFactoryCustomizer;
import
org.springframework.boot.web.servlet.server.ConfigurableServletWe
bServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

@Override
public void customize(ConfigurableServletWebServerFactory
server) {
server.setPort(9000);
}

}
TomcatServletWebServerFactory,
JettyServletWebServerFactory and
UndertowServletWebServerFactory are dedicated variants of
ConfigurableServletWebServerFactory that have additional
customization setter methods for Tomcat, Jetty and Undertow respectively.

Customizing ConfigurableServletWebServerFactory Directly


If the preceding customization techniques are too limited, you can register the
TomcatServletWebServerFactory, JettyServletWebServerFactory,
orUndertowServletWebServerFactory bean yourself.

@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new
TomcatServletWebServerFactory();
factory.setPort(9000);
factory.setSessionTimeout(10, TimeUnit.MINUTES);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
"/notfound.html"));
return factory;
}

Setters are provided for many configuration options. Several protected method “hooks” are
also provided should you need to do something more exotic. See the source code
documentation for details.

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 Jetty and Tomcat, it should work if you use war packaging. An executable war
will work when launched with java -jar, and will also be deployable to any
standard container. JSPs are not supported when using an executable jar.
● Undertow does not support JSPs.
● Creating a custom error.jsp page does not override the default view for error
handling. Custom error pages should be used instead.

There is a JSP sample so that you can see how to set things up.

Embedded Reactive Server Support


Spring Boot includes support for the following embedded reactive web servers: Reactor
Netty, Tomcat, Jetty, and Undertow. Most developers use the appropriate “Starter” to obtain
a fully configured instance. By default, the embedded server listens for HTTP requests on
port 8080.

Reactive Server Resources Configuration


When auto-configuring a Reactor Netty or Jetty server, Spring Boot will create specific beans
that will provide HTTP resources to the server instance: ReactorResourceFactory or
JettyResourceFactory.

By default, those resources will be also shared with the Reactor Netty and Jetty clients for
optimal performances, given:

● the same technology is used for server and client


● the client instance is built using the WebClient.Builder bean auto-configured
by Spring Boot

Developers can override the resource configuration for Jetty and Reactor Netty by providing
a custom ReactorResourceFactory or JettyResourceFactory bean - this will
be applied to both clients and servers.

You can learn more about the resource configuration on the client side in the WebClient
Runtime section.

Security
If Spring Security is on the classpath, then web applications are secured by default. Spring
Boot relies on Spring Security’s content-negotiation strategy to determine whether to use
httpBasic or formLogin. To add method-level security to a web application, you can
also add @EnableGlobalMethodSecurity with your desired settings. Additional
information can be found in the Spring Security Reference Guide.

The default UserDetailsService has a single user. The user name is user, and the
password is random and is printed at INFO level when the application starts, as shown in the
following example:

Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35


If you fine-tune your logging configuration, ensure that the
org.springframework.boot.autoconfigure.security category
is set to log INFO-level messages. Otherwise, the default password is not
printed.

You can change the username and password by providing a


spring.security.user.name and spring.security.user.password.

The basic features you get by default in a web application are:

● A UserDetailsService (or ReactiveUserDetailsService in case of a


WebFlux application) bean with in-memory store and a single user with a generated
password (see SecurityProperties.User for the properties of the user).
● Form-based login or HTTP Basic security (depending on Content-Type) for the entire
application (including actuator endpoints if actuator is on the classpath).
● A DefaultAuthenticationEventPublisher for publishing authentication
events.

You can provide a different AuthenticationEventPublisher by adding a bean for it.

MVC Security
The default security configuration is implemented in SecurityAutoConfiguration
and UserDetailsServiceAutoConfiguration.
SecurityAutoConfigurationimports
SpringBootWebSecurityConfiguration for web security and
UserDetailsServiceAutoConfiguration configures authentication, which is also
relevant in non-web applications. To switch off the default web application security
configuration completely, you can add a bean of type
WebSecurityConfigurerAdapter (doing so does not disable the
UserDetailsService configuration or Actuator’s security).

To also switch off the UserDetailsService configuration, you can add a bean of type
UserDetailsService, AuthenticationProvider, or
AuthenticationManager. There are several secure applications in the Spring Boot
samples to get you started with common use cases.

Access rules can be overridden by adding a custom


WebSecurityConfigurerAdapter. Spring Boot provides convenience methods that
can be used to override access rules for actuator endpoints and static resources.
EndpointRequest can be used to create a RequestMatcher that is based on the
management.endpoints.web.base-path property. PathRequest can be used to
create a RequestMatcher for resources in commonly used locations.

WebFlux Security
Similar to Spring MVC applications, you can secure your WebFlux applications by adding the
spring-boot-starter-security dependency. The default security configuration is
implemented in ReactiveSecurityAutoConfiguration and
UserDetailsServiceAutoConfiguration.
ReactiveSecurityAutoConfigurationimports
WebFluxSecurityConfiguration for web security and
UserDetailsServiceAutoConfiguration configures authentication, which is also
relevant in non-web applications. To switch off the default web application security
configuration completely, you can add a bean of type WebFilterChainProxy (doing so
does not disable the UserDetailsService configuration or Actuator’s security).

To also switch off the UserDetailsService configuration, you can add a bean of type
ReactiveUserDetailsService or ReactiveAuthenticationManager.

Access rules can be configured by adding a custom SecurityWebFilterChain. Spring


Boot provides convenience methods that can be used to override access rules for actuator
endpoints and static resources. EndpointRequest can be used to create a
ServerWebExchangeMatcher that is based on the
management.endpoints.web.base-path property.

PathRequest can be used to create a ServerWebExchangeMatcher for resources


in commonly used locations.

For example, you can customize your security configuration by adding something like:

@Bean
public SecurityWebFilterChain
springSecurityFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange()
.matchers(PathRequest.toStaticResources().atCommonLocations
()).permitAll()
.pathMatchers("/foo", "/bar")
.authenticated().and()
.formLogin().and()
.build();
}

OAuth2
OAuth2 is a widely used authorization framework that is supported by Spring.

Client
If you have spring-security-oauth2-client on your classpath, you can take
advantage of some auto-configuration to make it easy to set up an OAuth2/Open ID Connect
clients. This configuration makes use of the properties under
OAuth2ClientProperties. The same properties are applicable to both servlet and
reactive applications.

You can register multiple OAuth2 clients and providers under the
spring.security.oauth2.client prefix, as shown in the following example:

spring.security.oauth2.client.registration.my-client-1.client-id=abcd
spring.security.oauth2.client.registration.my-client-1.client-
secret=password
spring.security.oauth2.client.registration.my-client-1.client-name=Client
for user scope
spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-
provider
spring.security.oauth2.client.registration.my-client-1.scope=user
spring.security.oauth2.client.registration.my-client-1.redirect-uri-
template=http://my-redirect-uri.com
spring.security.oauth2.client.registration.my-client-1.client-
authentication-method=basic
spring.security.oauth2.client.registration.my-client-1.authorization-
grant-type=authorization_code

spring.security.oauth2.client.registration.my-client-2.client-id=abcd
spring.security.oauth2.client.registration.my-client-2.client-
secret=password
spring.security.oauth2.client.registration.my-client-2.client-name=Client
for email scope
spring.security.oauth2.client.registration.my-client-2.provider=my-oauth-
provider
spring.security.oauth2.client.registration.my-client-2.scope=email
spring.security.oauth2.client.registration.my-client-2.redirect-uri-
template=http://my-redirect-uri.com
spring.security.oauth2.client.registration.my-client-2.client-
authentication-method=basic
spring.security.oauth2.client.registration.my-client-2.authorization-
grant-type=authorization_code

spring.security.oauth2.client.provider.my-oauth-provider.authorization-
uri=http://my-auth-server/oauth/authorize
spring.security.oauth2.client.provider.my-oauth-provider.token-
uri=http://my-auth-server/oauth/token
spring.security.oauth2.client.provider.my-oauth-provider.user-info-
uri=http://my-auth-server/userinfo
spring.security.oauth2.client.provider.my-oauth-provider.user-info-
authentication-method=header
spring.security.oauth2.client.provider.my-oauth-provider.jwk-set-
uri=http://my-auth-server/token_keys
spring.security.oauth2.client.provider.my-oauth-provider.user-name-
attribute=name

For OpenID Connect providers that support OpenID Connect discovery, the configuration
can be further simplified. The provider needs to be configured with an issuer-uri which
is the URI that the it asserts as its Issuer Identifier. For example, if the issuer-uri
provided is "https://example.com", then an OpenID Provider Configuration
Request will be made to "https://example.com/.well-known/openid-configuration". The
result is expected to be an OpenID Provider Configuration Response. The
following example shows how an OpenID Connect Provider can be configured with the
issuer-uri:

spring.security.oauth2.client.provider.oidc-provider.issuer-
uri=https://dev-123456.oktapreview.com/oauth2/default/

By default, Spring Security’s OAuth2LoginAuthenticationFilter only processes


URLs matching /login/oauth2/code/*. If you want to customize the redirect-
uri to use a different pattern, you need to provide configuration to process that custom
pattern. For example, for servlet applications, you can add your own
WebSecurityConfigurerAdapter that resembles the following:

public class OAuth2LoginSecurityConfig extends


WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.redirectionEndpoint()
.baseUri("/custom-callback");
}
}

OAuth2 client registration for common providers


For common OAuth2 and OpenID providers, including Google, Github, Facebook, and Okta,
we provide a set of provider defaults (google, github, facebook, and okta,
respectively).

If you do not need to customize these providers, you can set the provider attribute to the
one for which you need to infer defaults. Also, if the key for the client registration matches a
default supported provider, Spring Boot infers that as well.

In other words, the two configurations in the following example use the Google provider:

spring.security.oauth2.client.registration.my-client.client-
id=abcd
spring.security.oauth2.client.registration.my-client.client-
secret=password
spring.security.oauth2.client.registration.my-
client.provider=google

spring.security.oauth2.client.registration.google.client-id=abcd
spring.security.oauth2.client.registration.google.client-
secret=password

Resource Server
If you have spring-security-oauth2-resource-server on your classpath,
Spring Boot can set up an OAuth2 Resource Server as long as a JWK Set URI or OIDC
Issuer URI is specified, as shown in the following examples:

spring.security.oauth2.resourceserver.jwt.jwk-set-
uri=https://example.com/oauth2/default/v1/keys
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-
123456.oktapreview.com/oauth2/default/

The same properties are applicable for both servlet and reactive applications.

Alternatively, you can define your own JwtDecoder bean for servlet applications or a
ReactiveJwtDecoder for reactive applications.
Authorization Server
Currently, Spring Security does not provide support for implementing an OAuth 2.0
Authorization Server. However, this functionality is available from the Spring Security OAuth
project, which will eventually be superseded by Spring Security completely. Until then, you
can use the spring-security-oauth2-autoconfigure module to easily set up an
OAuth 2.0 authorization server; see its documentation for instructions.

Actuator Security
For security purposes, all actuators other than /health and /info are disabled by
default. The management.endpoints.web.exposure.include property can be
used to enable the actuators.

If Spring Security is on the classpath and no other WebSecurityConfigurerAdapter is


present, all actuators other than /health and /info are secured by Spring Boot auto-
configuration. If you define a custom WebSecurityConfigurerAdapter, Spring Boot
auto-configuration will back off and you will be in full control of actuator access rules.

Before setting the


management.endpoints.web.exposure.include,
ensure that the exposed actuators do not contain sensitive
information and/or are secured by placing them behind a firewall
or by something like Spring Security.

Cross Site Request Forgery Protection


Since Spring Boot relies on Spring Security’s defaults, CSRF protection is turned on by
default. This means that the actuator endpoints that require a POST (shutdown and loggers
endpoints), PUT or DELETE will get a 403 forbidden error when the default security
configuration is in use.
We recommend disabling CSRF protection completely only if
you are creating a service that is used by non-browser clients.

Additional information about CSRF protection can be found in the Spring Security Reference
Guide.

Working with SQL Databases


The Spring Framework provides extensive support for working with SQL databases, from
direct JDBC access using JdbcTemplate to complete “object relational mapping”
technologies such as Hibernate. Spring Data provides an additional level of functionality:
creating Repository implementations directly from interfaces and using conventions to
generate queries from your method names.

Configure a DataSource
Java’s javax.sql.DataSource interface provides a standard method of working with
database connections. Traditionally, a 'DataSource' uses a URL along with some credentials
to establish a database connection.

See the “How-to” section for more advanced examples, typically


to take full control over the configuration of the DataSource.

Embedded Database Support


It is often convenient to develop applications by using an in-memory embedded database.
Obviously, in-memory databases do not provide persistent storage. You need to populate
your database when your application starts and be prepared to throw away data when your
application ends.

The “How-to” section includes a section on how to initialize a


database.

Spring Boot can auto-configure embedded H2, HSQL, and Derby databases. You need not
provide any connection URLs. You need only include a build dependency to the embedded
database that you want to use.

If you are using this feature in your tests, you may notice that the
same database is reused by your whole test suite regardless of the
number of application contexts that you use. If you want to make
sure that each context has a separate embedded database, you
should set spring.datasource.generate-unique-name

to true.

For example, the typical POM dependencies would be as follows:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
You need a dependency on spring-jdbc for an embedded
database to be auto-configured. In this example, it is pulled in
transitively throughspring-boot-starter-data-jpa.

If, for whatever reason, you do configure the connection URL for
an embedded database, take care to ensure that the database’s
automatic shutdown is disabled. If you use H2, you should use
DB_CLOSE_ON_EXIT=FALSE to do so. If you use HSQLDB,
you should ensure that shutdown=true is not used.
Disabling the database’s automatic shutdown lets Spring Boot
control when the database is closed, thereby ensuring that it
happens once access to the database is no longer needed.

Connection to a Production Database


Production database connections can also be auto-configured by using a pooling
DataSource. Spring Boot uses the following algorithm for choosing a specific
implementation:

1. We prefer HikariCP for its performance and concurrency. If HikariCP is available, we


always choose it.
2. Otherwise, if the Tomcat pooling DataSource is available, we use it.
3. If neither HikariCP nor the Tomcat pooling datasource are available and if Commons
DBCP2 is available, we use it.
If you use the spring-boot-starter-jdbc or spring-boot-starter-data-
jpa “starters”, you automatically get a dependency to HikariCP.

You can bypass that algorithm completely and specify the


connection pool to use by setting the
spring.datasource.type property. This is especially
important if you run your application in a Tomcat container, as
tomcat-jdbc is provided by default.

Additional connection pools can always be configured manually.


If you define your own DataSource bean, auto-configuration
does not occur.

DataSource configuration is controlled by external configuration properties in


spring.datasource.*. For example, you might declare the following section
inapplication.properties:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

You should at least specify the URL by setting the


spring.datasource.url property. Otherwise, Spring
Boot tries to auto-configure an embedded database.

You often do not need to specify the driver-class-name,


since Spring Boot can deduce it for most databases from the
url.

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

other words, if you set spring.datasource.driver-class-

name=com.mysql.jdbc.Driver, then that class has to be loadable.

See DataSourceProperties for more of the supported options. These are the
standard options that work regardless of the actual implementation. It is also possible to fine-
tune implementation-specific settings by using their respective prefix
(spring.datasource.hikari.*, spring.datasource.tomcat.*, and
spring.datasource.dbcp2.*). Refer to the documentation of the connection pool
implementation you are using for more details.

For instance, if you use the Tomcat connection pool, you could customize many additional
settings, as shown in the following example:

# Number of ms to wait before throwing an exception if no connection is


available.
spring.datasource.tomcat.max-wait=10000
# Maximum number of active connections that can be allocated from this
pool at the same time.
spring.datasource.tomcat.max-active=50

# Validate the connection before borrowing it from the pool.


spring.datasource.tomcat.test-on-borrow=true

Using JdbcTemplate
Spring’s JdbcTemplate and NamedParameterJdbcTemplate classes are auto-
configured, and you can @Autowire them directly into your own beans, as shown in the
following example:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

private final JdbcTemplate jdbcTemplate;

@Autowired
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

// ...

You can customize some properties of the template by using the


spring.jdbc.template.* properties, as shown in the following example:

spring.jdbc.template.max-rows=500
The NamedParameterJdbcTemplate reuses the same

JdbcTemplate instance behind the scenes. If more than one


JdbcTemplate is defined and no primary candidate exists,
the NamedParameterJdbcTemplate is not auto-
configured.

JPA and Spring Data JPA


The Java Persistence API is a standard technology that lets you “map” objects to relational
databases. The spring-boot-starter-data-jpa POM provides a quick way to get
started. It provides the following key dependencies:

● Hibernate: One of the most popular JPA implementations.


● Spring Data JPA: Makes it easy to implement JPA-based repositories.
● Spring ORMs: Core ORM support from the Spring Framework.

We do not go into too many details of JPA or Spring Data here.


You can follow the “Accessing Data with JPA” guide from
spring.io and read the Spring Data JPA and Hibernate reference
documentation.

Entity Classes
Traditionally, JPA “Entity” classes are specified in a persistence.xml file. With Spring
Boot, this file is not necessary and “Entity Scanning” is used instead. By default, all
packages below your main configuration class (the one annotated with
@EnableAutoConfiguration or @SpringBootApplication) are searched.

Any classes annotated with @Entity, @Embeddable, or @MappedSuperclass are


considered. A typical entity class resembles the following example:

package com.example.myapp.domain;
import java.io.Serializable;
import javax.persistence.*;

@Entity
public class City implements Serializable {

@Id
@GeneratedValue
private Long id;

@Column(nullable = false)
private String name;

@Column(nullable = false)
private String state;

// ... additional members, often include @OneToMany mappings

protected City() {
// no-args constructor required by JPA spec
// this one is protected since it shouldn't be used directly
}

public City(String name, String state) {


this.name = name;
this.state = state;
}

public String getName() {


return this.name;
}

public String getState() {


return this.state;
}

// ... etc
}

You can customize entity scanning locations by using the


@EntityScan annotation. See the “Section 83.4, “Separate
@Entity Definitions from Spring Configuration”” how-to.

Spring Data JPA Repositories


Spring Data JPA repositories are interfaces that you can define to access data. JPA queries
are created automatically from your method names. For example, aCityRepository
interface might declare a findAllByState(String state) method to find all the
cities in a given state.

For more complex queries, you can annotate your method with Spring Data’s Query
annotation.

Spring Data repositories usually extend from the Repository or CrudRepository


interfaces. If you use auto-configuration, repositories are searched from the package
containing your main configuration class (the one annotated with
@EnableAutoConfiguration or @SpringBootApplication) down.

The following example shows a typical Spring Data repository interface definition:

package com.example.myapp.domain;

import org.springframework.data.domain.*;
import org.springframework.data.repository.*;

public interface CityRepository extends Repository<City, Long> {

Page<City> findAll(Pageable pageable);

City findByNameAndStateAllIgnoringCase(String name, String state);

}
Spring Data JPA repositories support three different modes of bootstrapping: default,
deferred, and lazy. To enable deferred or lazy bootstrapping, set
thespring.data.jpa.repositories.bootstrap-mode to deferred or lazy
respectively. When using deferred or lazy bootstrapping, the auto-configured
EntityManagerFactoryBuilder will use the context’s AsyncTaskExecutor, if
any, as the bootstrap executor. If more than one exists, the one named
applicationTaskExecutor will be used.

We have barely scratched the surface of Spring Data JPA. For


complete details, see the Spring Data JPA reference
documentation.

Creating and Dropping JPA Databases


By default, JPA databases are automatically created only if you use an embedded database
(H2, HSQL, or Derby). You can explicitly configure JPA settings by usingspring.jpa.*
properties. For example, to create and drop tables you can add the following line to your
application.properties:

spring.jpa.hibernate.ddl-auto=create-drop

Hibernate’s own internal property name for this (if you happen
to remember it better) is hibernate.hbm2ddl.auto. You
can set it, along with other Hibernate native properties, by using
spring.jpa.properties.* (the prefix is stripped before
adding them to the entity manager). The following line shows an
example of setting JPA properties for Hibernate:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

The line in the preceding example passes a value of true for the
hibernate.globally_quoted_identifiers property to the Hibernate entity
manager.

By default, the DDL execution (or validation) is deferred until the ApplicationContext
has started. There is also a spring.jpa.generate-ddl flag, but it is not used if
Hibernate auto-configuration is active, because the ddl-auto settings are more fine-
grained.

Open EntityManager in View


If you are running a web application, Spring Boot by default registers
OpenEntityManagerInViewInterceptor to apply the “Open EntityManager in
View” pattern, to allow for lazy loading in web views. If you do not want this behavior, you
should set spring.jpa.open-in-view to false in your
application.properties.

Spring Data JDBC


Spring Data includes repository support for JDBC and will automatically generate SQL for
the methods on CrudRepository. For more advanced queries, a @Queryannotation is
provided.

Spring Boot will auto-configure Spring Data’s JDBC repositories when the necessary
dependencies are on the classpath. They can be added to your project with a single
dependency on spring-boot-starter-data-jdbc. If necessary, you can take
control of Spring Data JDBC’s configuration by adding the
@EnableJdbcRepositoriesannotation or a JdbcConfiguration subclass to your
application.

For complete details of Spring Data JDBC, please refer to the


reference documentation.

Using H2’s Web Console


The H2 database provides a browser-based console that Spring Boot can auto-configure for
you. The console is auto-configured when the following conditions are met:

● You are developing a servlet-based web application.


● com.h2database:h2 is on the classpath.
● You are using Spring Boot’s developer tools.

If you are not using Spring Boot’s developer tools but would still
like to make use of H2’s console, you can configure the
spring.h2.console.enabledproperty with a value of
true.

The H2 console is only intended for use during development, so


you should take care to ensure that
spring.h2.console.enabled is not set to true in
production.

Changing the H2 Console’s Path


By default, the console is available at /h2-console. You can customize the console’s
path by using the spring.h2.console.path property.

Using jOOQ
Java Object Oriented Querying (jOOQ) is a popular product from Data Geekery which
generates Java code from your database and lets you build type-safe SQL queries through
its fluent API. Both the commercial and open source editions can be used with Spring Boot.
Code Generation
In order to use jOOQ type-safe queries, you need to generate Java classes from your
database schema. You can follow the instructions in the jOOQ user manual. If you use the
jooq-codegen-maven plugin and you also use the spring-boot-starter-
parent “parent POM”, you can safely omit the plugin’s <version> tag. You can also use
Spring Boot-defined version variables (such as h2.version) to declare the plugin’s
database dependency. The following listing shows an example:

<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<executions>
...
</executions>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<configuration>
<jdbc>
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/yourdatabase</url>
</jdbc>
<generator>
...
</generator>
</configuration>
</plugin>

Using DSLContext
The fluent API offered by jOOQ is initiated through the org.jooq.DSLContext
interface. Spring Boot auto-configures a DSLContext as a Spring Bean and connects it to
your application DataSource. To use the DSLContext, you can @Autowire it, as
shown in the following example:

@Component
public class JooqExample implements CommandLineRunner {
private final DSLContext create;

@Autowired
public JooqExample(DSLContext dslContext) {
this.create = dslContext;
}

The jOOQ manual tends to use a variable named create to

hold the DSLContext.

You can then use the DSLContext to construct your queries, as shown in the following
example:

public List<GregorianCalendar> authorsBornAfter1980() {


return this.create.selectFrom(AUTHOR)
.where(AUTHOR.DATE_OF_BIRTH.greaterThan(new
GregorianCalendar(1980, 0, 1)))
.fetch(AUTHOR.DATE_OF_BIRTH);
}

Working with NoSQL Technologies


Spring Data provides additional projects that help you access a variety of NoSQL
technologies, including: MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire,Cassandra,
Couchbase and LDAP. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j,
Elasticsearch, Solr Cassandra, Couchbase, and LDAP. You can make use of the other
projects, but you must configure them yourself. Refer to the appropriate reference
documentation at projects.spring.io/spring-data.

Working with NoSQL Technologies


Spring Data provides additional projects that help you access a variety of NoSQL
technologies, including: MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire,Cassandra,
Couchbase and LDAP. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j,
Elasticsearch, Solr Cassandra, Couchbase, and LDAP. You can make use of the other
projects, but you must configure them yourself. Refer to the appropriate reference
documentation at projects.spring.io/spring-data.

Redis
Redis is a cache, message broker, and richly-featured key-value store. Spring Boot offers
basic auto-configuration for the Lettuce and Jedis client libraries and the abstractions on top
of them provided by Spring Data Redis.

There is a spring-boot-starter-data-redis “Starter” for collecting the


dependencies in a convenient way. By default, it uses Lettuce. That starter handles both
traditional and reactive applications.

we also provide a spring-boot-starter-data-redis-

reactive “Starter” for consistency with the other stores with


reactive support.

Connecting to Redis
You can inject an auto-configured RedisConnectionFactory,
StringRedisTemplate, or vanilla RedisTemplate instance as you would any other
Spring Bean. By default, the instance tries to connect to a Redis server at
localhost:6379. The following listing shows an example of such a bean:

@Component
public class MyBean {

private StringRedisTemplate template;

@Autowired
public MyBean(StringRedisTemplate template) {
this.template = template;
}

// ...

}
You can also register an arbitrary number of beans that implement
LettuceClientConfigurationBuilderCustomizer for more
advanced customizations. If you use Jedis,
JedisClientConfigurationBuilderCustomizer is also
available.

If you add your own @Bean of any of the auto-configured types, it replaces the default
(except in the case of RedisTemplate, when the exclusion is based on the bean name,
redisTemplate, not its type). By default, if commons-pool2 is on the classpath, you
get a pooled connection factory.

You might also like