Using Spring Boot without the Parent POM
Not everyone likes inheriting from the spring-boot-starter-parent
POM. You may have your own corporate standard parent that you need to use or you may prefer to explicitly declare all your Maven configuration.
If you do not want to use the spring-boot-starter-parent
, you can still keep the benefit of the dependency management (but not the plugin management) by using a scope=import
dependency, as follows:
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The preceding sample setup does not let you override individual dependencies by using a property, as explained above. To achieve the same result, you need to add an entry in the dependencyManagement
of your project before the spring-boot-dependencies
entry. For instance, to upgrade to another Spring Data release train, you could add the following element to your pom.xml
:
<dependencyManagement>
<dependencies>
<!-- Override Spring Data release train provided by Spring Boot -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Fowler-SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
In the preceding example, we specify a BOM, but any dependency type can be overridden in the same way.
Not everyone likes inheriting from the
spring-boot-starter-parent
POM. You may have your own corporate standard parent that you need to use or you may prefer to explicitly declare all your Maven configuration.
If you do not want to use the
spring-boot-starter-parent
, you can still keep the benefit of the dependency management (but not the plugin management) by using a scope=import
dependency, as follows:<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The preceding sample setup does not let you override individual dependencies by using a property, as explained above. To achieve the same result, you need to add an entry in the
dependencyManagement
of your project before the spring-boot-dependencies
entry. For instance, to upgrade to another Spring Data release train, you could add the following element to your pom.xml
:<dependencyManagement>
<dependencies>
<!-- Override Spring Data release train provided by Spring Boot -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Fowler-SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
In the preceding example, we specify a BOM, but any dependency type can be overridden in the same way. |
1.2.3. 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.
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. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa
dependency in your project.
The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
The following application starters are provided by Spring Boot under the org.springframework.boot
group:
Table 1. Spring Boot application starters
Name Description Pom
Core starter, including auto-configuration support, logging and YAML
Starter for JMS messaging using Apache ActiveMQ
Starter for using Spring AMQP and Rabbit MQ
Starter for aspect-oriented programming with Spring AOP and AspectJ
Starter for JMS messaging using Apache Artemis
Starter for using Spring Batch
Starter for using Spring Framework’s caching support
Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku. Deprecated in favor of Java CFEnv
Starter for using Cassandra distributed database and Spring Data Cassandra
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive
Starter for using Couchbase document-oriented database and Spring Data Couchbase
Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch
Starter for using Spring Data JDBC
Starter for using Spring Data JPA with Hibernate
Starter for using Spring Data LDAP
Starter for using MongoDB document-oriented database and Spring Data MongoDB
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive
Starter for using Neo4j graph database and Spring Data Neo4j
Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client
Starter for exposing Spring Data repositories over REST using Spring Data REST
Starter for using the Apache Solr search platform with Spring Data Solr
Starter for building MVC web applications using FreeMarker views
Starter for building MVC web applications using Groovy Templates views
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS
Starter for using Spring Integration
Starter for using JDBC with the HikariCP connection pool
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web
Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa
or spring-boot-starter-jdbc
Starter for reading and writing json
Starter for JTA transactions using Atomikos
Starter for JTA transactions using Bitronix
Starter for using Java Mail and Spring Framework’s email sending support
Starter for building web applications using Mustache views
Starter for using Spring Security’s OAuth2/OpenID Connect client features
Starter for using Spring Security’s OAuth2 resource server features
Starter for using the Quartz scheduler
Starter for building RSocket clients and servers.
Starter for using Spring Security
Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito
Starter for building MVC web applications using Thymeleaf views
Starter for using Java Bean Validation with Hibernate Validator
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
Starter for using Spring Web Services
Starter for building WebFlux applications using Spring Framework’s Reactive Web support
Starter for building WebSocket applications using Spring Framework’s WebSocket support
In addition to the application starters, the following starters can be used to add production ready features:
Table 2. Spring Boot production starters
Name Description Pom
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application
Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets:
Table 3. Spring Boot technical starters
Name Description Pom
Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat
Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging
Starter for logging using Logback. Default logging starter
Starter for using Reactor Netty as the embedded reactive HTTP server.
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web
Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat
For a list of additional community contributed starters, see the README file in the spring-boot-starters
module on GitHub.
Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the
spring-boot-starter-data-jpa
dependency in your project.
The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
The following application starters are provided by Spring Boot under the
org.springframework.boot
group:Name | Description | Pom |
---|---|---|
Core starter, including auto-configuration support, logging and YAML
| ||
Starter for JMS messaging using Apache ActiveMQ
| ||
Starter for using Spring AMQP and Rabbit MQ
| ||
Starter for aspect-oriented programming with Spring AOP and AspectJ
| ||
Starter for JMS messaging using Apache Artemis
| ||
Starter for using Spring Batch
| ||
Starter for using Spring Framework’s caching support
| ||
Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku. Deprecated in favor of Java CFEnv
| ||
Starter for using Cassandra distributed database and Spring Data Cassandra
| ||
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive
| ||
Starter for using Couchbase document-oriented database and Spring Data Couchbase
| ||
Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive
| ||
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch
| ||
Starter for using Spring Data JDBC
| ||
Starter for using Spring Data JPA with Hibernate
| ||
Starter for using Spring Data LDAP
| ||
Starter for using MongoDB document-oriented database and Spring Data MongoDB
| ||
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive
| ||
Starter for using Neo4j graph database and Spring Data Neo4j
| ||
Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client
| ||
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client
| ||
Starter for exposing Spring Data repositories over REST using Spring Data REST
| ||
Starter for using the Apache Solr search platform with Spring Data Solr
| ||
Starter for building MVC web applications using FreeMarker views
| ||
Starter for building MVC web applications using Groovy Templates views
| ||
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS
| ||
Starter for using Spring Integration
| ||
Starter for using JDBC with the HikariCP connection pool
| ||
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to
spring-boot-starter-web | ||
Starter for using jOOQ to access SQL databases. An alternative to
spring-boot-starter-data-jpa or spring-boot-starter-jdbc | ||
Starter for reading and writing json
| ||
Starter for JTA transactions using Atomikos
| ||
Starter for JTA transactions using Bitronix
| ||
Starter for using Java Mail and Spring Framework’s email sending support
| ||
Starter for building web applications using Mustache views
| ||
Starter for using Spring Security’s OAuth2/OpenID Connect client features
| ||
Starter for using Spring Security’s OAuth2 resource server features
| ||
Starter for using the Quartz scheduler
| ||
Starter for building RSocket clients and servers.
| ||
Starter for using Spring Security
| ||
Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito
| ||
Starter for building MVC web applications using Thymeleaf views
| ||
Starter for using Java Bean Validation with Hibernate Validator
| ||
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
| ||
Starter for using Spring Web Services
| ||
Starter for building WebFlux applications using Spring Framework’s Reactive Web support
| ||
Starter for building WebSocket applications using Spring Framework’s WebSocket support
|
In addition to the application starters, the following starters can be used to add production ready features:
Name | Description | Pom |
---|---|---|
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application
|
Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets:
Name | Description | Pom |
---|---|---|
Starter for using Jetty as the embedded servlet container. An alternative to
spring-boot-starter-tomcat | ||
Starter for using Log4j2 for logging. An alternative to
spring-boot-starter-logging | ||
Starter for logging using Logback. Default logging starter
| ||
Starter for using Reactor Netty as the embedded reactive HTTP server.
| ||
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by
spring-boot-starter-web | ||
Starter for using Undertow as the embedded servlet container. An alternative to
spring-boot-starter-tomcat |
For a list of additional community contributed starters, see the README file in the spring-boot-starters module on GitHub. |
2. Structuring Your Code
Spring Boot does not require any specific code layout to w
Spring Boot does not require any specific code layout to w
1.1. 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);
}
When your application starts, you should see something similar to the following output:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: v2.3.0.BUILD-SNAPSHOT 2019-04-31 13:09:54.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb) 2019-04-31 13:09:54.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy 2019-04-01 13:09:56.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080 2019-04-01 13:09:57.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658)
By default,
INFO
logging messages are shown, including some relevant startup details, such as the user that launched the application. If you need a log level other than INFO
, you can set it, as described in Log Levels. The application version is determined using the implementation version from the main application class’s package. Startup information logging can be turned off by setting spring.main.log-startup-info
to false
. This will also turn off logging of the application’s active profiles.To add additional logging during startup, you can override logStartupInfo(boolean) in a subclass of SpringApplication . |
1.2. 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.
Spring Boot provides numerous FailureAnalyzer implementations, and you can add your own. |
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.ConditionEvaluationReportLoggingListener
.
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
1.3. Lazy Initialization
SpringApplication
allows an application to be initialized lazily. When lazy initialization is enabled, beans are created as they are needed rather than during application startup. As a result, enabling lazy initialization can reduce the time that it takes your application to start. In a web application, enabling lazy initialization will result in many web-related beans not being initialized until an HTTP request is received.
A downside of lazy initialization is that it can delay the discovery of a problem with the application. If a misconfigured bean is initialized lazily, a failure will no longer occur during startup and the problem will only become apparent when the bean is initialized. Care must also be taken to ensure that the JVM has sufficient memory to accommodate all of the application’s beans and not just those that are initialized during startup. For these reasons, lazy initialization is not enabled by default and it is recommended that fine-tuning of the JVM’s heap size is done before enabling lazy initialization.
Lazy initialization can be enabled programatically using the
lazyInitialization
method on SpringApplicationBuilder
or the setLazyInitialization
method on SpringApplication
. Alternatively, it can be enabled using the spring.main.lazy-initialization
property as shown in the following example:spring.main.lazy-initialization=true
1.4. 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
1.5. 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.
If you have specified any files in spring.config.location
, profile-specific variants of those files are not considered. Use directories in spring.config.location
if you want to also use profile-specific properties.
1.6 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 property
and 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)
.
1.6.1. Application Property Files
SpringApplication
loads properties from application.properties
files in the following locations and adds them to the Spring Environment
:
-
A
/config
subdirectory of the current directory
-
The current directory
-
A classpath
/config
package
-
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:/override.properties
28. Creating Your Own Starter
A full Spring Boot starter for a library may contain the following components:
- The
autoconfigure
module that contains the auto-configuration code. - The
starter
module that provides a dependency to theautoconfigure
module as well as the library and any additional dependencies that are typically useful. In a nutshell, adding the starter should provide everything needed to start using that library.
You may combine the auto-configuration code and the dependency management in a single module if you do not need to separate those two concerns. |
28.1. Naming
You should make sure to provide a proper namespace for your starter. Do not start your module names with
spring-boot
, even if you use a different Maven groupId
. We may offer official support for the thing you auto-configure in the future.
As a rule of thumb, you should name a combined module after the starter. For example, assume that you are creating a starter for "acme" and that you name the auto-configure module
acme-spring-boot-autoconfigure
and the starter acme-spring-boot-starter
. If you only have one module that combines the two, name it acme-spring-boot-starter
.28.2. Configuration keys
If your starter provides configuration keys, use a unique namespace for them. In particular, do not include your keys in the namespaces that Spring Boot uses (such as
server
, management
, spring
, and so on). If you use the same namespace, we may modify these namespaces in the future in ways that break your modules. As a rule of thumb, prefix all your keys with a namespace that you own (e.g. acme
).
Make sure that configuration keys are documented by adding field javadoc for each property, as shown in the following example:
@ConfigurationProperties("acme")
public class AcmeProperties {
/**
* Whether to check the location of acme resources.
*/
private boolean checkLocation = true;
/**
* Timeout for establishing a connection to the acme server.
*/
private Duration loginTimeout = Duration.ofSeconds(3);
// getters & setters
}
You should only use simple text with @ConfigurationProperties field Javadoc, since they are not processed before being added to the JSON. |
Here are some rules we follow internally to make sure descriptions are consistent:
- Do not start the description by "The" or "A".
- For
boolean
types, start the description with "Whether" or "Enable". - For collection-based types, start the description with "Comma-separated list"
- Use
java.time.Duration
rather thanlong
and describe the default unit if it differs from milliseconds, e.g. "If a duration suffix is not specified, seconds will be used". - Do not provide the default value in the description unless it has to be determined at runtime.
Make sure to trigger meta-data generation so that IDE assistance is available for your keys as well. You may want to review the generated metadata (
META-INF/spring-configuration-metadata.json
) to make sure your keys are properly documented. Using your own starter in a compatible IDE is also a good idea to validate that quality of the metadata.
autoconfigure
Module
28.3.
The
autoconfigure
module contains everything that is necessary to get started with the library. It may also contain configuration key definitions (such as @ConfigurationProperties
) and any callback interface that can be used to further customize how the components are initialized.You should mark the dependencies to the library as optional so that you can include the autoconfigure module in your projects more easily. If you do it that way, the library is not provided and, by default, Spring Boot backs off. |
Spring Boot uses an annotation processor to collect the conditions on auto-configurations in a metadata file (
META-INF/spring-autoconfigure-metadata.properties
). If that file is present, it is used to eagerly filter auto-configurations that do not match, which will improve startup time. It is recommended to add the following dependency in a module that contains auto-configurations:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>
0 comments :
Post a Comment