This is most common exception when connecting with database through Spring boot application. It’s happen because of connection failed to the database.
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed. Error: "ABCKXYZ356.
Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port.
Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:285) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2434) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:659) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2546) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2216) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2067) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1204) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:825) ~[mssql-jdbc-8.2.1.jre8.jar:na]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar:na]
Reason of Exception
These are main reason of this Exception:
This issue can occurred because of wrong properties configured for database connection.
This issue can also occurred if the database is not running.
This issue can also occurred if database only allow to access through vpn.
Solutions
These are some most common solution to resolve this issue:
Verify the connection properties.
Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port.
Make sure that TCP connections to the port are not blocked by a firewall.
Check the vpn connection if DB access allow over the vpn.
Hope these solutions help you to resolve this issue. Please share in comments.
LIQUIBASE is a provider of Spring Boot Data for handling database schemas operations. LIQUIBASE is an Open Source tool which keep track of database schema script revisions. It can handle variety of database types and accepts a variety of file formats for defining the database structures.
After adding LIQUIBASE dependencies in your application it will automatically download and add the required other dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Liquibase Configuration Properties
Spring Boot load these properties in LiquibaseProperties class.
ApacheCassandra is a provider of Spring Boot Data for handling NoSQL database operations. Apache Cassandra is a NoSQL distributed database for managing large amounts of data across many servers (clusters) while providing high availability at the cost of decreased consistency. Cassandra high availability is achieved by replicating data to multiple nodes over cluster and allow one or more nodes to go down so that transaction will continue till that point even one server is running.
To use Apache Cassandra in your Spring boot application you have to add this Cassandra starter in your pom.xml .
After adding Cassandra Database starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Cassandra Configuration Properties
Spring Boot load these properties in CassandraProperties class.
Name
Default Value
Description
spring.data.cassandra.cluster-name
Cassandra cluster Name.
spring.data.cassandra.compression
Compression supported by the Cassandra binary protocol.
Couchbase is a provider of Spring Boot for handling NoSQL database operations through JSON. Couchbase is NoSQL document oriented distributed database over the cloud or on- premises which perform transactions by JSON and provide unmatched versatility, performance and scalability. To use Couchbase in your Spring boot application you have to add this Couchbase starter in your pom.xml .
After adding Couchbase Database starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Data Couchbase Configuration Properties
Spring Boot load these properties in CouchbaseDataProperties class.
Name
Default Value
Description
spring.data.couchbase.auto-index
false
create views and indexes automatically.
spring.data.couchbase.consistency
read-your-own-writes
By default Consistency to apply on generated queries.
spring.data.couchbase.repositories.enabled
true
Enable Couchbase repositories.
Data Couch Spring Boot properties
Couchbase Configuration Properties
Spring Boot load these properties in CouchbaseProperties class.
Name
Default Value
Description
spring.couchbase.bootstrap-hosts
Couchbase nodes host/IP address to bootstrap from.
spring.couchbase.bucket.name
default
bucket name connect to.
spring.couchbase.bucket.password
bucket password.
spring.couchbase.env.endpoints.key-value
1
Number of sockets per node for each Key/value service.
spring.couchbase.env.endpoints.query
1
Number of sockets per node for each Query (N1QL) service.
spring.couchbase.env.endpoints.view
1
Number of sockets per node for each view service.
spring.couchbase.env.ssl.enabled
Enable SSL support. Enabled automatically if a “keyStore” is provided otherwise specified otherwise.
spring.couchbase.env.ssl.key-store
Path to JVM key store which holds the certificates.
spring.couchbase.env.ssl.key-store-password
Password used to access the key store.
spring.couchbase.env.timeouts.connect
5000
Bucket connections timeout. (in milliseconds)
spring.couchbase.env.timeouts.key-value
2500
Blocking operations performed on a key timeout.( in milliseconds)
spring.couchbase.env.timeouts.query
7500
N1QL query operations timeout.( in milliseconds)
spring.couchbase.env.timeouts.socket-connect
1000
Socket connect connections timeout.( in milliseconds).
spring.couchbase.env.timeouts.view
7500
Regular and geospatial view operations timeout. (in milliseconds).
Apache SOLR is a provider of Spring Boot for handling search and indexing of data operations on SOLR content for web. SOLR is a Full Text search engine for content management and also provide REST based SOLR APIs for operations. To use SOLR in your Spring boot application you have to add this SOLR starter in your pom.xml .
After adding SOLR starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
SOLR Configuration Properties
Spring Boot load these properties in SolrProperties class.
Elasticsearch is a provider of Spring Boot for handling search and CRUD operations in Elastic Search. Elasticsearch is a Full Text search engine and also provide REST based Elasticsearch APIs for operations. To use Elastic Search in your Spring boot application you have to add this Elasticsearch starter in your pom.xml .
After adding Elasticsearch starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
ElasticSearch Configuration Properties
Spring Boot load these properties in ElasticsearchProperties class.
Name
Default Value
Description
spring.data.elasticsearch.cluster-name
elasticsearch
cluster name.
spring.data.elasticsearch.cluster-nodes
Comma-separated cluster node addresses. If not specified, starts a client node.
spring.data.elasticsearch.properties.*
Additional properties used to configure the client.
spring.data.elasticsearch.repositories.enabled
true
Enable Elasticsearch repositories.
Elastic Search Spring Boot Properties
JEST (Elasticsearch HTTP client) Configuration Properties
Spring Boot load these properties in JestProperties class.
MongoDB is a provider of Spring Boot for handling NoSQL database operations. To use MongoDB in your Spring boot application you have to add this MongoDB starter in your pom.xml .
After adding MongoDB starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Embedded MongoDB Configuration Properties
Spring Boot load these properties in EmbeddedMongoProperties class.
Name
Default Value
Description
spring.mongodb.embedded.features
SYNC_DELAY
Comma-separated features to enable.
spring.mongodb.embedded.storage.database-dir
Directory used for data storage.
spring.mongodb.embedded.storage.oplog-size
Maximum size of the oplog in megabytes.
spring.mongodb.embedded.storage.repl-set-name
Name of the replica set.
spring.mongodb.embedded.version
2.6.10
Version of Mongo to use.
MongoDB Embedded Spring Boot Properties
MongoDB Configuration Properties
Spring Boot load these properties in MongoProperties class.
Name
Default Value
Description
spring.data.mongodb.authentication-database
Authentication database name.
spring.data.mongodb.database
test
Database name.
spring.data.mongodb.field-naming-strategy
USe Fully qualified name of the FieldNamingStrategy.
spring.data.mongodb.grid-fs-database
GridFS database name.
spring.data.mongodb.host
localhost
Mongo server host.
spring.data.mongodb.password
Login password of the mongo server.
spring.data.mongodb.port
27017
Mongo server port.
spring.data.mongodb.repositories.enabled
true
Enable Mongo repositories.
spring.data.mongodb.uri
mongodb://localhost/test
Mongo database URI.host and port are ignored when setting it.
Neo4J is a provider of Spring Boot for handling Graphical database. Neo4J is a graphical datbase where need to represent stored data in graphical relational forms. You can add Neo4J in your Spring boot application by adding Neo4J starter in your pom.xml (Maven) or build.gradle (Gradle).
After adding Neo4J starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Neo4j Configuration Properties
Spring Boot load these properties in Neo4jProperties class.
Name
Default Value
Description
spring.data.neo4j.compiler
Compiler to use.
spring.data.neo4j.embedded.enabled
true
Enable embedded mode when embedded driver is available.
ATOMIKOS is a provider of Spring Boot for handling transactions atomicity in global transactions involving heterogeneous components. To use ATOMIKOS transaction manager in your Spring boot application you have to add this ATOMIKOS starter in your pom.xml .
After adding ATOMIKOS starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Atomikos Configuration Properties
Spring Boot load these properties in AtomikosProperties class.
BITRONIX is a provider of Spring Boot for handling distributed transaction. To use BITRONIX transaction manager in your Spring boot application you have to add this BITRONIX starter in your pom.xml .
After adding BITRONIX starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .
Narayana is a popular open source JTA transaction manager implementation supported by Red Hat. To use Narayana JTA in your Spring Boot application you can use You can use the narayana-spring-boot-starter starter to add the appropriate Narayana dependencies to your application.
Spring Boot automatically configures Narayana with default values and post-processes your beans to ensure that startup and shutdown ordering is correct.
NARAYANA Spring Boot Properties
Spring Boot load these properties in NarayanaProperties class with default values you can overwrite these values in your application application.properties/ application.yaml.
Interval in which periodic recovery scans are performed.(in second)
spring.jta.narayana.recovery-backoff-period
10
Back off period between first and second phases of the recovery scan.(in second)
spring.jta.narayana.recovery-db-pass
Database password for recovery manager.
spring.jta.narayana.recovery-db-user
Database username for recovery manager.
spring.jta.narayana.recovery-jms-pass
JMS password for recovery manager.
spring.jta.narayana.recovery-jms-user
JMS username for recovery manager.
spring.jta.narayana.recovery-modules
Comma-separated recovery modules.
spring.jta.narayana.transaction-manager-id
1
Unique transaction manager id.
spring.jta.narayana.xa-resource-orphan-filters
Comma-separated orphan filters.
By default, Narayana transaction logs written location is transaction-logs directory in your application home directory (the directory in which your application jar file resides). You can customize the location of this directory by setting the narayana.log-dir or spring.jta.log-dir similar to that you can also customize the other properties.
In Spring Boot application, you can set the JVM parameters by two ways so that increase the JVM heap size, in case required you can also configure the other parameters like GC alogorithms, MetaSpace etc.
Configure Parameters in pom.xml: To pass the JVM parameters for an application , we can set these parameters in spring-boot-maven-plugin in pom.xml plugin section.
In the previous post , Spring Boot Actuator : : Monitor Health of Application you have learn about the Spring Boot actuator enabling and access health monitoring parameters through Spring Boot Actuator provided endpoints (default).
In this post, You will learn about to create custom Spring Boot Actuator end points. Sometimes these custom actuator endpoints required to get some specific information or customization of information instead of providing all detailed application health related information.
You have to follow these steps in Spring Boot application to create custom actuator endpoints.
Step 1:
Create or import any Spring Boot REST application. For Example using for User related Rest service (CRUD).
Step 2:
Enable the actuator in Spring Boot application by adding actuator starter in application pom.xml
By default actuator allows external access for endpoints /actuator /health and /info, to access others custom actuator endpoints. you have add this property in your application.properties file.
management.endpoints.web.exposure.include=*
Now, start your application and see the actuator is working fine or not by trying below url. If your server running on port 8090.
Now to create custom actuator endpoints , you can create a class MyUserEndPoints in package com.facingIssuesOnIT.actuator as below:
To create a new endpoint you have to create a class and annotate it with @Component and @Endpoint annotation. The @Endpoint annotation has a parameter id (Ex: users) which determines the URL path of endpoint. This class contains the methods which returns the response of the endpoint.
The value of id parameter of @Endpoint is users. So this endpoint is accessible by URL /actuator/users.
a method defined with @ReadOperation which will be mapped to HTTP GET method and automatically be exposed over HTTP.
a method defined with @WriteOperation which will be mapped to HTTP POST method and automatically be exposed over HTTP. The methods that are annotated with @WriteOperation can take parameters in JSON format alone.
a method defined with @DeleteOperation which will be mapped to HTTP DELETE method and automatically be exposed over HTTP.
technology-specific endpoints defined with @WebEndpoint/@JmxEndpoint. For ex, @WebEndpoint is exposed over HTTP only.
Step 5:
Restart the application and try with different custom actuator end points as below:
Once Spring Boot application deployed into production environment, you always want to monitor the application. This is because you want to ensure that the application must be always up and running and in case of any issues you want to fix it quickly. Therefore, an application monitoring tool is required so that you can analyze the health of your application.
Spring Boot has an in-built mechanism for monitoring application called as Actuator. It is a sub-project of Spring Boot. It offers several production grades features to monitor the application. Once you enable actuator in your Spring Boot application, a set of endpoints are exposed using which you can monitor and manage your application. You can also integrate these endpoints with other application monitoring tools such Prometheus, Graphite etc.
Now let us see how you can enable Actuator in your Spring Boot application.
Spring Boot Actuator Configuration
Actuators can be easily enabled in your application by adding following spring-boot-actuator dependency in pom.xml file:
Once Actuator is enabled in your application, using actuator endpoints you can monitor and manage your application. These endpoints are exposed over HTTP in Spring MVC application using the ‘id’ of endpoints as the URL path along with /actuator as prefix. The following table shows some important actuator endpoints:
Actuator Endpoints
Description
/beans
Provides list of all Spring beans available in the application
/configprops
Provides a collated list of all @ConfigurationProperties
/env
Exposes all the properties from Spring’s Configurable Environment
/info
Displays arbitrary application information
/metrics
Displays metric information for the current application
/mappings
Displays a collated list of all request mapping paths
/shutdown
Allows the application to shutdown
/trace
Displays trace information, by default latest 100 HTTP requests
/health
Provides applications health information
Spring Boot Actuator Endpoints
Note : By default spring boot actuator only only allow the access of /health and /info end points because other end points provide application sensitive information.
You can also access the other specific end points by making below changes in your application.properties / application.yml file.
Access actuator all endpoints
You can add below properties to access all the end points:
#Access all actuator endpoints
management.endpoints.web.exposure.include=*
Restrict specific actuator endpoints
You can add below exclude property to restrict the specific urls:
#Access all actuator endpoints
management.endpoints.web.exposure.include=*
#Retrict env endpoints to access
management.endpoints.web.exposure.exclude=env
If you want to restrict access for more than one endpoints the specify as comma separated:
#Access all actuator endpoints
management.endpoints.web.exposure.include=*
#Retrict env endpoints to access
management.endpoints.web.exposure.exclude=env,beans
We will discuss on all the spring boot actuator end points in further sections.
If your application is running application on port number 8090, you can use below end point to get list of all the actuator endpoints and it will give you following response:
Now in further section will use the above endpoints of actuator and show the response of each API’s call.
Endpoint /health
This actuator health endpoint gives you the information about health of application. You can access this endpoint using the URL http://localhost:8090/actuator/health. It will give you following response:
{"status":"UP"}
The status will be UP if application is running and healthy. If application has some issues such as database is down etc. then you will get following response:
{"status":"DOWN"}
It tells only whether the status of application is UP or DOWN. If you want to get details information about health of application then add the following property in the application.properties file:
If you noticed from above response, it’s connected with database H2 and application consuming data disc spaces.
Endpoint /metrics
This actuator metrics endpoint displays various metrics options that can be checked for your application. You can access this endpoint using the URL http://localhost:8090/actuator/metrics. It will give you following response :
The above metrics endpoint response has the name of individual metric. To get more information about these metrics you need to append the metric name to the URL. For example if you want to know more about jvm.memory.used metric then the URL will be http://localhost:8090/actuator/metrics/jvm.memory.used. This URL will give the following response:
{
"name": "jvm.memory.used",
"description": "The amount of used memory",
"baseUnit": "bytes",
"measurements": [
{
"statistic": "VALUE",
"value": 1.67400072E8
}
],
"availableTags": [
{
"tag": "area",
"values": [
"heap",
"nonheap"
]
},
{
"tag": "id",
"values": [
"G1 Old Gen",
"CodeHeap 'non-profiled nmethods'",
"G1 Survivor Space",
"Compressed Class Space",
"Metaspace",
"G1 Eden Space",
"CodeHeap 'non-nmethods'"
]
}
]
}
According to above response, you can get you application JVM memory space consumption, Garbage collectors configure etc.
Same way you can explore more about the application configuration, http requests hits, beans creation information by using actuators other endpoints.
A spring boot application starts from the main class (class with main() method) that contains main method with below signature. On Startup of spring boot application it create Spring ApplicationContext and beans also for application..
@SpringBootApplication
public class SpringBootMainClassApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMainClassApplication.class, args);
}
}
By default spring boot search the main class in the class path at compile time. if it’s find multiple main class or none then it will throw exception as below.
Spring Boot Application without Main class
While running the application through STS/Eclipse it will show popup as “Selection does not contain a main type”.
Spring Boot Application without Main Class
Spring Boot Application with multiple main class
If you run the application manually through STS/Eclipse then you have to select one of the Main class below before execution. If you are trying to maven package of install from CMD it will throw exception as below.
mvn package -Dmaven.test.skip=true
it will through exception as below in CMD.
Spring Boot Application with Multiple Main Class
Solutions
To start a Spring Boot application, it’s mandatory to specify one Main class in your class path. If there is one Main class as above then will not be any issue to start a Spring boot application.
Now if there are multiple main class in your Spring Boot application then below solutions will help to start your application.
Solution 1: Specify the Main class in pom.xml properties
You can specify your main class in property start-class as below.
<properties>
<!-- The spring boot main class to start by executing "java -jar" -->
<start-class>com.FacingIssuesOnIT.SpringBootMainClassApplication</start-class>
</properties>
Note : This property configuration will help only when you added the spring-boot-starter-parent as in your pom.xml otherwise follow the solutions 2 or 3 to configure the main class.
Solution 2 : Specify the Main class in spring-boot-maven-plugin of pom.xml
You can also specify the main class of Spring Boot in spring-boot-maven-plugin of pom.xml as below:
By using any of these configuration, You can decide you Spring Boot application main class for start the application.
Conclusion
In this post you learn about the different way to configure Spring Boot Application main class to start the application if your application having multiple Main classes.
In Spring Boot Rest/MVC application, we got this exception “java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘XYZController’ method” which will not allow to create bean for your controller and also throw “UnsatisfiedDependencyException: Error creating bean with name XYZ” as given in below stack trace.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/C:/Users/saurabh.gupta14/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/C:/Users/saurabh.gupta14/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1354) ~[spring-beans-5.3.9.jar:5.3.9]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/C:/Users/saurabh.gupta14/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1354) ~[spring-beans-5.3.9.jar:5.3.9]
... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.9.jar:5.3.9]
... 41 common frames omitted
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.validateMethodMapping(AbstractHandlerMethodMapping.java:665) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:631) ~[spring-webmvc-5.3.9.jar:5.3.9]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:328) ~[spring-webmvc-5.3.9.jar:5.3.9]
... 55 common frames omitted
Reason of Exception
The exception “java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘xyzController’ method” is throw when there is end point of REST urls of two method are same with Verb in your application. So on time of deploy your spring boot application the dispatcher servlet will create mapping of urls with respect to method because two methods having the same name with http verb (GET/POST/PUT/DELETE) then dispatcher got confuse for particular url which method need to point and throw this exception “java.lang.IllegalStateException: Ambiguous mapping”.
Solution
As explained above the reason of this exception. Once this exception happen check for the recently added urls for REST services . This url can be same with in same controller of your application where the exception occurred or match with other controller if no request mapping on class level.
In Spring Boot by default configure for Banner “Spring Boot” as below which will display on your console with version number.
Spring Boot Banner
Possible Values for Spring Boot Banner
Spring Boot support these three types of configuration for Banner:
OFF : Disable printing of Banner
CONSOLE : Display Banner to System.out
LOG : Display Banner on your Log also.
How to set these Spring Boot Banner Configuration?
There are two ways to configure Spring Boot Banner:
Banner setting by application.properties / applictaion.yml
You can add this property in application.properties/ application.yml file to change in configuration of Banner. If you set as off will not display in console and log.
##possible values off, console, log
spring
main
banner-mode:console
Banner Setting in Spring Boot main() method
You can also change in Spring Boot class main() method to set Banner configuration as below in this case no setting required on application properties file.
Spring Boot Banner Setting
Customize Spring Boot Banner
By default Spring Boot show default banner “Spring Boot” with version number. If you want to customize this banner and replace it then create one banner.txt file and place it on your Spring boot application resource folder.
In Spring boot Data JPA this exception QueryCreationException occurred when there is auto creation of Query or mismatch or column name in column/property in Entity class.
Spring Data JPA supports two ways of creating auto generation of query:
JQL in Spring data JPA or HQL when using the Hibernate.
Spring Data methods in Repository interface for Example : findByUserName() or findByUserNameOrDesignation() etc.
Reason for Exception
Spring Data JPA generate queries based on name of property in your Entity class , If entity based custom methods defined in repository interfaces also generate queries internally based on method name.
If there is any mismatch or incorrect name in custom methods of repository interface when comparing to entity class properties then on compile time it will not through any issue but when you run or deploy spring boot application will through QueryCreationException: Could not create query for method XYZ.
For Example : In User Entity class there is property userName while in custom methods in repository, you are trying to get detail from method findByName() so this property name not exist in User Entity class . Till compile time this method will not show any issue and compile successfully while on deploy time because using Spring Data JPA so will try to fetch data by Name and it will through exception as QueryCreationException: Could not create query for method XYZ.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userrepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.FacingIssuesOnIT.repository.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! Reason: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.9.jar:5.3.9]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.FacingIssuesOnIT.repository.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! Reason: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
... 25 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! Reason: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.3.jar:2.5.3]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.3.jar:2.5.3]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.3.jar:2.5.3]
... 35 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.5.3.jar:2.5.3]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:107) ~[spring-data-jpa-2.5.3.jar:2.5.3]
... 57 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property username found for type User!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.3.jar:2.5.3]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.3.jar:2.5.3]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.3.jar:2.5.3]
... 61 common frames omitted
Solutions
To solve “QueryCreationException” in Spring boot data JPA follow these steps:
Go to stack trace of exception and see which query and methods of repository interface is throwing the exception.
Go to repository interface where this particular query and methods are defined and also check the Entity name with respect to repository.
Go to Entity class and check the properties name defined in method/queries are same or not.
If it’s not same or some typing mistake then only you will get this exception.
Note: Whenever you change any property name / column name in Entity class then always check for dependency in Native Queries/ JQL/HQL and Custom methods in repository otherwise your application will not deploy and fail on runtime.
One common tomcat web server issue is directory listing that’s can cause to hackers attacked. By default tomcat directory listing is enabled or some developers set as enabled then it’s create a Information Disclosure Issue(leakage of sensitive information).
In your website/application if directory listing is enabled and index page is not configured as index.html or index.php then on typing the context path or URL till directory will display the list of directory and file as below and user/hacker can see all these files sensitive information.
Tomcat Directory Listing Enabled
As you can see from the above screenshot, the directory listing feature generates an output similar to command (‘dir’ or ‘ls’) on an operating system. Directory listing issues can not protect from a SSL certificate. However, These types of issue can be identified by running through vulnerabilities scanner on your application through Microfocus Web inspect.
Solutions
As a solution to disable directory listing depends on the tomcat server because in some of Spring boot application use tomcat as embedded server:
Disable directory listing on embedded tomcat in Spring boot
Disable directory listing on external tomcat server
Disable directory Listing on embedded tomcat in Spring boot
In Spring boot application where tomcat is defined as embedded tomcat then the application is deployed as jar and there is no web.xml file the you have to define this property setting on your application.properties / application.yml file to disable directory listing.
server.servlet.jsp.init-parameters.listings=false
Disable directory listing on external tomcat server
When you deploy your application using package as war on external tomcat server then you have to make these changes on your web.xml file to disable the directory listing on external tomcat server.
Here in above xml in web.xml file the init-param tag for listing is defined as false to disable the directory listing for application on web application.
f you are using the other web servers then you can check these configuration through below link.
Spring Boot comes with lots of default configuration that’s already defined in its application.propertie internal file. When we use spring-boot-starter-parent that’s add all these spring boot default properties in your application.
If your business required change on these default values then you can override it by writing in your application.properties/application.yaml file. On-time on initialization for application properties spring boot will override these default values with your mentioned configuration.
In the previous example, we are using the default spring boot embedded tomcat server port as 8080. It means when we launch our spring boot application embedded server will start on port 8080. Now for changing the embedded tomcat server port add this below property in your application.properties file.
server.port=8090
Now run this spring boot application example, because now embedded tomcat server is running on port 8090 so calling your application services now you have to use port 8090 instead of 8080.
Spring Boot Common properties with Default Value
For better understanding, I have categorized list of Spring Boot common properties in different categories so that you can focus as per your need.
Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.
These are Spring Boot Data properties that can be configured with any Spring Boot Application. These properties are already configured in Spring Boot with the given default value.
Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.
These are Spring Boot Security Configuration Properties that can be configured with any Spring Boot Web Application. These properties are already configured in Spring Boot with the given default value.
Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.
These are Spring Boot Integration properties that can be configured with any Spring Boot Application. These properties are already configured in Spring Boot with the given default value.
Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.
These are Spring Boot Dev Tools properties that can be configured with any Spring Boot Application. These properties are already configured in Spring Boot with the given default value.
Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.
These are Web application common properties that can be configured with any Spring Boot Web Application. These properties are already configured in Spring Boot with the given default value.
Note: In your application, You don’t need to add all these values in your application.proprties/application.yaml file. You just need to add only those values which you want to change/override.
Spring Boot load these properties in ServerProperties
Name
Default Value
Description
server.address
Network address for the server.
server.compression.enabled
false
To enable response compression.
server.compression.excluded-user-agents
user-agents list to exclude from compression.
server.compression.mime-types
Comma-separated MIME typesist that should be compressed. For instance `text/html,text/css,application/json`
server.compression.min-response-size
Minimum response size for compression. For instance 2048
server.connection-timeout
Connectors wait time (in MilliSeconds) for another HTTP request before closing the connection. If not set then take default as container-specific. If set as -1 for infinite time out.
server.context-parameters.*
Servlet context init parameters. For example `server.context-parameters.a=alpha`
server.context-path
Application Context path.
server.display-name
application
Display application name.
server.max-http-header-size
0
Maximum size in bytes for HTTP msg header.
server.max-http-post-size
0
Maximum size in bytes for HTTP post content.
server.error.include-stacktrace
never
When to include a “stacktrace” attribute.
server.error.path
/error
Path of navigate in case of the error.
server.error.whitelabel.enabled
true
Enable the default error page displayed in case of a server error.
server.jetty.acceptors
Number of acceptor threads to use.
server.jetty.selectors
Number of selector threads to use.
server.jsp-servlet.class-name
org.apache.jasper.servlet.JspServlet
The class name of the JSP servlet.
server.jsp-servlet.init-parameters.*
Init parameters used to configure the JSP servlet.
server.jsp-servlet.registered
true
Whether or not the JSP servlet is registered.
server.port
8080
HTTP Server port.
server.server-header
Server response header value (no header is sent if empty)
server.servlet-path
/
Path of the main dispatcher servlet.
server.use-forward-headers
If X-Forwarded-* headers should be applied in HttpRequest.
server.session.cookie.comment
Comment for the session cookie.
server.session.cookie.domain
Domain for the session cookie.
server.session.cookie.http-only
“HttpOnly” flag for the session cookie.
server.session.cookie.max-age
Maximum age of the session cookie in seconds.
server.session.cookie.name
Session cookie name.
server.session.cookie.path
Path of the session cookie.
server.session.cookie.secure
“Secure” flag for the session cookie.
server.session.persistent
false
Persist session data between restarts.
server.session.store-dir
Directory used to store session data.
server.session.timeout
Session timeout in seconds
server.session.tracking-modes
Session tracking modes either one or more in “cookie”, “url”, “ssl”.
server.ssl.ciphers
Supported SSL ciphers.
server.ssl.client-auth
Set client authentication is “want” or “need”. Requires a trust store.
server.ssl.enabled
Enable SSL support.
server.ssl.enabled-protocols
Enabled SSL protocols.
server.ssl.key-alias
Alias for identifies the key in the key store.
server.ssl.key-password
Password for access the key in the key store.
server.ssl.key-store
Path to the key store that holds the SSL certificate (jks file).
server.ssl.key-store-provider
Provider for the key store.
server.ssl.key-store-type
Type of the key store.
server.ssl.protocol
TLS
SSL protocol to use.
server.ssl.trust-store
Trust store that holds SSL certificates.
server.ssl.trust-store-password
Password used to access the trust store.
server.ssl.trust-store-provider
Provider for the trust store.
server.ssl.trust-store-type
Type of the trust store.
server.tomcat.accesslog.directory
logs
Directory in which log files are created. i.e tomcat base dir or absolute.
server.tomcat.accesslog.enabled
false
Enable access log.
server.tomcat.accesslog.pattern
common
Format pattern for access logs.
server.tomcat.accesslog.prefix
access_log
Log file name prefix.
server.tomcat.accesslog.rename-on-rotate
false
Defer inclusion of the date stamp in the file name as long as rotate time.
Spring Boot load these properties in SessionProperties class.
Name
Default Value
Description
spring.session.hazelcast.map-name
spring:session:sessions
Name of the map used to store sessions.
spring.session.jdbc.initializer.enabled
If necessary, Create the required session tables on startup if necessary. Enabled automatically if the default a custom schema is configured or table name is set.
These are core properties that can be configured with any Spring Boot Application. These properties are already configured in Spring Boot with the given default value.
Note: In your application, You don’t need to add all these values in your application.proprties/ application.YAML file. You just need to add only those values which you want to change/override.
If images need to inverted for dark terminal themes.
Logging Properties
Name
Default Value
Description
logging.config
Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word
%wEx
Conversion word used when logging exceptions.
logging.file
Log file name. For instance `myapp.log`
logging.level.*
Log levels severity mapping. For instance logging.level.org.springframework=DEBUG
logging.path
Location of the log file. For instance ‘/var/log’
logging.pattern.console
Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file
Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level
Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook
false
Register a shutdown hook on time of initialization for the logging system.
AOP Properties
Name
Default Value
Description
spring.aop.auto
true
Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class
false
false when Standard Java interface-based proxies. true when subclass-based (CGLIB) proxies.
Application Identity Properties
Spring Boot load these properties in ContextIdApplicationContextInitializer class.
Name
Default Value
Description
spring.application.index
Application index.
spring.application.name
Application name
Admin Properties
Spring Boot load these properties in SpringApplicationAdminJmxAutoConfiguration class.
Name
Default Value
Description
spring.application.admin.enabled
false
Enable admin features for the application.
spring.application.admin.jmx-name
org.springframework.boot:type=Admin,name=SpringApplication #JMX name of the application admin MBean.
Auto Configuration Properties
Name
Default Value
Description
spring.autoconfigure.exclude
Auto-configuration classes to exclude.
Spring Core Properties
Name
Default Value
Description
spring.beaninfo.ignore
true
Skip search of BeanInfo classes.
Spring Cache Properties
Spring Boot load these properties in CacheProperties class.
Name
Default Value
Description
spring.cache.cache-names
If supported by cache manager, then mentioned Comma-separated list.
spring.cache.caffeine.spec
The specification to use to create caches. For Example: Check CaffeineSpec for more details on the spec format.
spring.cache.couchbase.expiration
0
By default the entries never expire(You can write in milliseconds).
spring.cache.ehcache.config
Configuration file location to initialize EhCache.
spring.cache.guava.spec
The specification to use to create caches.For Example: Check CacheBuilderSpec for more details on the spec format.
spring.cache.hazelcast.config
Configuration file location to initialize Hazelcast.
spring.cache.infinispan.config
Configuration file location to initialize Infinispan.
spring.cache.jcache.config
Configuration file location to initialize the cache manager
spring.cache.jcache.provider
Fully qualified name of the Cache Provider implementation to use to retrieve the JSR-107 compliant cache manager. It only required if more than one JSR-107 implementation is available on the classpath.
spring.cache.type
Cache type, auto-detected according to the environment.
Spring Config Properties
Spring Boot load these properties in ConfigFileApplicationListener class when using environment properties.
Name
Default Value
Description
spring.config.location
Config file locations
spring.config.name
application
Config file name.
HAZELCAST Properties
Spring Boot load these properties in HazelcastProperties class.
Name
Default Value
Description
spring.hazelcast.config
The location of the configuration file to initialize Hazelcast.
Project Information Properties
Spring Boot load these properties in ProjectInfoProperties class.
Name
Default Value
Description
spring.info.build.location
classpath:META-INF/build-info.properties
Location for generated build-info.properties file.
spring.info.git.location
classpath:git.properties
Location generforated git.properties file.
JMX Properties
Name
Default Value
Description
spring.jmx.default-domain
JMX domain name.
spring.jmx.enabled
true
Expose management beans for JMX domain.
spring.jmx.server
mbeanServer
MBeanServer bean name.
Email Properties
Spring Boot load these properties in MailProperties class.
Name
Default Value
Description
spring.mail.default-encoding
UTF-8
Default MimeMessage encoding.
spring.mail.host
SMTP server host. For instance ‘smtp.example.com’
spring.mail.jndi-name
Session JNDI name. When set, takes precedence to others mail settings.
spring.mail.password
Login password of the SMTP server.
spring.mail.port
SMTP server port.
spring.mail.properties.*
Additional JavaMail session properties
spring.mail.protocol
smtp
Protocol used by the SMTP server.
spring.mail.test-connection
false
Mail server is available on startup.
spring.mail.username
Login user of the SMTP server.
Application Settings Properties
Spring Boot load these properties in SpringApplication class.
Name
Default Value
Description
spring.main.banner-mode
console
Mode for display the banner when the application startup.
spring.main.sources
Sources (class name, package name or XML resource location) in the ApplicationContext.
spring.main.web-environment
Run the application in a web environment. it auto-detected by default.
File Encoding Properties
Spring Boot load these properties in FileEncodingApplicationListener class.
Name
Default Value
Description
spring.mandatory-file-encoding
Expected character encoding the application must use.
Internationalization Properies
Spring Boot load these properties in MessageSourceAutoConfiguration class.
Name
Default Value
Description
spring.messages.always-use-message-format
false
Setting whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename
messages
Comma-separated list of basenames and each following the ResourceBundle convention.
spring.messages.cache-seconds
-1
Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding
UTF-8
Message bundles encoding.
spring.messages.fallback-to-system-locale
true
Setting to fall back to the system Locale if no files for a specific Locale have been found.
Output Properties
Name
Default Value
Description
spring.output.ansi.enabled
detect
Configure the ANSI output.
PID FILE Properties
Spring Boot load these properties in ApplicationPidFileWriter class.
Name
Default Value
Description
spring.pid.fail-on-write-error
Fail if ApplicationPidFileWriter is used but not write the PID file.
spring.pid.file
Location to PID file to write. if ApplicationPidFileWriter is used.
Profile Properties
Name
Default Value
Description
spring.profiles.active
A comma-separated list of active profiles.
spring.profiles.include
Unconditionally activate the specified comma separated profiles
SENDGRID Properties
Spring Boot load these properties in SendGridAutoConfiguration class.
Name
Default Value
Description
spring.sendgrid.api-key
SendGrid api key (alternative to username/password)
In the previous article, you have learned about Spring Boot System Requirements. In this article, you will learn about steps to create Spring Boot Application in the Maven environment.
Check Java Version
Check Maven Version
Create Application in Maven
Add Spring Boot Parent
Add spring-boot-stater-
Add Business Functionality
Build & Run
Here you will know in detail about each step.
Check Java Version
You can run command java -version to get the current java version installed in your machine.
Added highlighted lines of the statement in pom.xml to make your application Spring Boot Web Application.
Let’s discuss in detail these three sections.
spring-boot-starter-parent: It’s a special starter that inherits useful maven defaults. It also provides dependency management so that omit version tags for dependencies.
spring-boot-starter-web: It’s add in the dependencies section to make application as a web which will add all required dependencies for a web application.
spring-boot-maven-plugin: This plugin is used to create an executable jar of your application.
Add Business Functionality
Now your application is having Spring Boot features. You can add your business functionality as per requirement. In this below code we can create one REST service which returns the response as “Hello World!”.
Here this main method is the starting point of your Spring Boot application that will start Spring container, create beans, load configuration and perform required actions to start the application.
@RestController: This is stereotype annotation which helps to understand the users and Spring framework like whats the purpose of this class like Spring will consider this class when any web request will come.
@RequestMapping: This annotation provides routing information. In this example, tell Spring that any HTTP request with the path “/” should be mapped to the home method.
@EnableAutoConfiguration: This is class-level annotation, which tells to spring boot to guess how you want to configure spring based on configured starters in classpaths and jars. Since in pom.xml we have added spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume you want to develop a web-based application.
Build & Run
To build your application just go to the root directory of the application and run below command.
mvn package
When you run this command it will take time because download required dependencies from maven repository and after successful compile and package. It will create one more folder as a target in the root of your application.
When an application successfully executed then got to the browser and in address bar use this URL http://localhost:8080 after submit you will get a response as “Hello World!!”.
Spring Boot supports the number of “Starters” that make developer life easy so that more focus on functionality implementation instead of thing about dependencies and it’s version. If any starter is added then it will add all dependent jars in your classpath.
To get your application dependency list using command mvn dependency:tree which represents dependencies in the form of a tree. You can use the command as below:
mvn dependency:tree
Spring Boot Starters
Here is a list of Spring Boot Starters which used for adding specific features to your application.
Name
Description
spring-boot-starter-parent
Use for core starter, logging, YAML support, and auto-configuration.
spring-boot-starter-web
Use for building web, RESTful, applications using Spring MVC. By default embedded tomcat container.
spring-boot-starter-aop
Use for AOP with Spring AOP and AspectJ.
spring-boot-starter-data-jpa
Use for Spring Data JPA with Hibernate.
spring-boot-starter-test
Use to test application with libraries including JUnit, Mockito and Hamcrest.
spring-boot-starter-jdbc
Use for JDBC with the Tomcat JDBC connection pool.
spring-boot-starter-thymeleaf
Use to build MVC web applications using Thymeleaf views.
spring-boot-starter-data-couchbase
Use for Couchbase document-oriented database and Spring Data Couchbase.
spring-boot-starter-artemis
Use for JMS messaging using Apache Artemis.
spring-boot-starter-web-services
Use for Spring Web Services.
spring-boot-starter-mail
Use to support Java Mail and Spring Framework’s email sending.
spring-boot-starter-data-redis
Use for Redis key-value data store with Spring Data Redis and the Jedis client.
spring-boot-starter-data-gemfire
Use to GemFire distributed data store and Spring Data GemFire.
spring-boot-starter-activemq
Use to JMS messaging using Apache ActiveMQ.
spring-boot-starter-data-elasticsearch
Use to Elasticsearch search and analytics engine and Spring Data Elasticsearch.
spring-boot-starter-integration
Use for Spring Integration.
spring-boot-starter-mobile
Use for building web applications using Spring Mobile.
spring-boot-starter-validation
Use for Java Bean Validation with Hibernate Validator.
spring-boot-starter-hateoas
Use to build a hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS.
spring-boot-starter-jersey
Use to build RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web.
spring-boot-starter-data-neo4j
Use for the Neo4j graph database and Spring Data Neo4j.
spring-boot-starter-data-ldap
Use for Spring Data LDAP.
spring-boot-starter-websocket
Use for building WebSocket. applications using Spring Framework?s WebSocket support.
spring-boot-starter-amqp
Use for Spring AMQP and Rabbit MQ.
spring-boot-starter-data-cassandra
Use for Cassandra distributed database and Spring Data Cassandra.
spring-boot-starter-social-facebook
Use for Spring Social Facebook.
spring-boot-starter-jta-atomikos
Use for JTA transactions using Atomikos.
spring-boot-starter-security
Use for Spring Security.
spring-boot-starter-mustache
Use for building MVC web applications using Mustache views.
spring-boot-starter-groovy-templates
Use for building MVC web applications using Groovy Templates’ views.
spring-boot-starter-freemarker
Use to build MVC web applications by FreeMarker views.
spring-boot-starter-batch
Use for Spring Batch.
spring-boot-starter-social-linkedin
Use for Spring Social LinkedIn.
spring-boot-starter-cache
Use for Spring Framework’s caching support.
spring-boot-starter-data-solr
Use for the Apache Solr search platform with Spring Data Solr.
spring-boot-starter-data-mongodb
Use for MongoDB document-oriented database and Spring Data MongoDB.
spring-boot-starter-jooq
Use for jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc.
spring-boot-starter-jta-narayana
Use for Spring Boot Narayana JTA Starter.
spring-boot-starter-cloud-connectors
Use for Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku.
spring-boot-starter-jta-bitronix
Use for JTA transactions using Bitronix.
spring-boot-starter-social-twitter
Use for Spring Social Twitter.
spring-boot-starter-data-rest
Use for exposing Spring Data repositories over REST using Spring Data REST.
Spring Boot starters for Technical
Name
Description
spring-boot-starter-tomcat
Use for Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web.
spring-boot-starter-undertow
Use for Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat.
spring-boot-starter-jetty
Use for Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat.
spring-boot-starter-logging
Use for logging using Logback. Default logging starter.
spring-boot-starter-log4j2
Use for Log4j2 for logging. An alternative to spring-boot-starter-logging.
Spring Boot starters for Production
Name
Description
spring-boot-starter-actuator
The actuator provides production-ready features for monitor, audit and manages your application.
spring-boot-starter-remote-shell
CRaSH remote shell use to monitor and manage your application over SSH. Deprecated since 1.5.
Spring Boot is a Spring module that provides the RAD feature to the Spring framework. Spring Boot makes easy to create a stand-alone, production-based application that can “just run” with very little configuration. It doesn’t generate code and not require an XML configuration.
You can create a Java application that can run by command java -jar or create traditional web application by creating war and deploy on the server.
Note:
Spring Boot Current Version: 5.2.4 Release (February 25, 2020)
You must be logged in to post a comment.