Category Archives: Spring Boot

Spring Boot : Set JVM Parameters for an Application


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.
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>-Xms512m -Xmx1024m -XX:+UseZGC -XX:MaxMetaspaceSize=512m</jvmArguments>
    </configuration>
</plugin>
  • Pass JVM parameters through Command line: We can pass the JVM parameters through the command line while running the Spring Boot application jar file.
java -jar zyz-service.jar -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m -XX:+UseZGC -XX:MaxMetaspaceSize=512m"

Note: In both the cases these parameters are as below :

  • -Xms512m : Minimum heap size allocate for JVM as 512 MB.
  • -Xmx1024m : Max heap size can be allocate for JVM as 1024 MB.
  • -XX:+UseZGC : Garbage collection algorithm as Z Garbage Collector.
  • -XX:MaxMetaspaceSize=512m : By default in Java 8 or after the MetaSpace size is unlimited but we can configure fix Max limit also.

Let me know the your thought on this post. If this was helpful for make a comment.

Happy Learning !!!

Spring Boot: Custom Actuator EndPoints Creation


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

<dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-actuator</artifactId>  
</dependency>

Step 3:

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.

http://localhost:8090/actuator/health

{"status":"UP"}

UP status shows your application is running fine.

See More : Spring Boot Actuator : : Monitor Health of Application

Step 4:

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. 

package com.FacingIssuesOnIT.actuators;

impert java.util.List;
impert java.util.Optional;

impert org.springframework.beans.factory.annotation.Autowired;
impert org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
impert org.springframework.boot.actuate.endpoint.annotation.Endpoint;
impert org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
impert org.springframework.boot.actuate.endpoint.annotation.Selector;
impert org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
impert org.springframework.core.env.Environment;
impert org.springframework.stereotype.Component;

impert com.FacingIssuesOnIT.model.User;
impert com.FacingIssuesOnIT.repository.UserRepository;

at2Component
at2Endpoint(id = "users")
public class MyUserEndpoints {
	
		at2Autowired
		private UserRepository userRepository;
		
		at2Autowired
		private Environment environment;
		
		at2ReadOperation
		public List<User> getAllUsers(){
			List<User> users =  userRepository.findAll();			
			return users;
		}
		
		at2WriteOperation
	    public String updateUser(Integer userId, String emailId) throws Exception {
		Optional<User> optional = userRepository.findById(userId);
			User user = optional.orElseThrow(() -> new Exception("Service.USER_NOT_FOUND"));
			user.setEmail(emailId);			
		return environment.getProperty("API.UPDATE_SUCCESS");
	}
		
		at2DeleteOperation
		public String deleteUser(at2Selector Integer userId) {
			userRepository.deleteById(userId);
			return environment.getProperty("API.DELETE_SUCCESS");
		}		
} 

In above class,

  • The value of id parameter of @Endpoint is usersSo 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:

GET Method : http://localhost:8090/actuator/users

Response: Existing users list

Spring Boot Custom Actuator Endpoints : Get Method

POST Method : http://localhost:8090/actuator/users

Request Body

Spring Boot Actuator Endpoints : Post Method

It will create new user sunny with Id 345

Delete Method: http://localhost:8090/actuator/users/3

Spring Boot Actuator Endpoints : Delete Method

Here you have seen the custom actuator endpoints urls and response through the postman.

Conclusion

In this post you have learn about the below points:

  • Spring Boot Actuator configuration and enabling
  • Spring Boot custom actuator endpoints creation steps.
  • Spring Boot custom actuator endpoints access through Postman.

Let me know your thought on this post.

Happy Learning !!!

Spring Boot Actuator : : Monitor Health of Application


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:

<dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-actuator</artifactId>  
</dependency> 

See More : Spring Boot: Custom Actuator EndPoints Creation

Actuator Endpoints

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 EndpointsDescription
/beansProvides list of all Spring beans available in the application
/configpropsProvides a collated list of all @ConfigurationProperties
/envExposes all the properties from Spring’s Configurable Environment
/infoDisplays arbitrary application information
/metricsDisplays metric information for the current application
/mappingsDisplays a collated list of all request mapping paths
/shutdownAllows the application to shutdown
/traceDisplays trace information, by default latest 100 HTTP requests
/healthProvides 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:

http://localhost:8090/actuator

Endpoint /actuator

By default actuator endpoint return only endpoints for /info and /health only as below.

Response:

{
	"_links": {
		"self": {
			"href": "http://localhost:8090/actuator",
			"templated": false
		},
		"health": {
			"href": "http://localhost:8090/actuator/health",
			"templated": false
		},
		"health-path": {
			"href": "http://localhost:8090/actuator/health/{*path}",
			"templated": true
		}
	}
}

If your actuator is enabled for all the endpoints as below then you will get complete list of end points of actuator:

#Access all actuator endpoints
management.endpoints.web.exposure.include=* 

Response:

{
	"_links": {
		"self": {
			"href": "http://localhost:8090/actuator",
			"templated": false
		},
		"beans": {
			"href": "http://localhost:8090/actuator/beans",
			"templated": false
		},
		"caches": {
			"href": "http://localhost:8090/actuator/caches",
			"templated": false
		},
		"caches-cache": {
			"href": "http://localhost:8090/actuator/caches/{cache}",
			"templated": true
		},
		"health": {
			"href": "http://localhost:8090/actuator/health",
			"templated": false
		},
		"health-path": {
			"href": "http://localhost:8090/actuator/health/{*path}",
			"templated": true
		},
		"info": {
			"href": "http://localhost:8090/actuator/info",
			"templated": false
		},
		"conditions": {
			"href": "http://localhost:8090/actuator/conditions",
			"templated": false
		},
		"configprops": {
			"href": "http://localhost:8090/actuator/configprops",
			"templated": false
		},
		"configprops-prefix": {
			"href": "http://localhost:8090/actuator/configprops/{prefix}",
			"templated": true
		},
		"env-toMatch": {
			"href": "http://localhost:8090/actuator/env/{toMatch}",
			"templated": true
		},
		"env": {
			"href": "http://localhost:8090/actuator/env",
			"templated": false
		},
		"loggers": {
			"href": "http://localhost:8090/actuator/loggers",
			"templated": false
		},
		"loggers-name": {
			"href": "http://localhost:8090/actuator/loggers/{name}",
			"templated": true
		},
		"heapdump": {
			"href": "http://localhost:8090/actuator/heapdump",
			"templated": false
		},
		"threaddump": {
			"href": "http://localhost:8090/actuator/threaddump",
			"templated": false
		},
		"metrics-requiredMetricName": {
			"href": "http://localhost:8090/actuator/metrics/{requiredMetricName}",
			"templated": true
		},
		"metrics": {
			"href": "http://localhost:8090/actuator/metrics",
			"templated": false
		},
		"scheduledtasks": {
			"href": "http://localhost:8090/actuator/scheduledtasks",
			"templated": false
		},
		"mappings": {
			"href": "http://localhost:8090/actuator/mappings",
			"templated": false
		}
	}
}

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:

management.endpoint.health.show-details=always
{
	"status": "UP",
	"components": {
		"db": {
			"status": "UP",
			"details": {
				"database": "H2",
				"validationQuery": "isValid()"
			}
		},
		"diskSpace": {
			"status": "UP",
			"details": {
				"total": 300662386688,
				"free": 277733244928,
				"threshold": 10485760,
				"exists": true
			}
		},
		"ping": {
			"status": "UP"
		}
	}
}

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 :

{
	"names": [
		"hikaricp.connections",
		"hikaricp.connections.acquire",
		"hikaricp.connections.active",
		"hikaricp.connections.creation",
		"hikaricp.connections.idle",
		"hikaricp.connections.max",
		"hikaricp.connections.min",
		"hikaricp.connections.pending",
		"hikaricp.connections.timeout",
		"hikaricp.connections.usage",
		"http.server.requests",
		"jdbc.connections.active",
		"jdbc.connections.idle",
		"jdbc.connections.max",
		"jdbc.connections.min",
		"jvm.buffer.count",
		"jvm.buffer.memory.used",
		"jvm.buffer.total.capacity",
		"jvm.classes.loaded",
		"jvm.classes.unloaded",
		"jvm.gc.live.data.size",
		"jvm.gc.max.data.size",
		"jvm.gc.memory.allocated",
		"jvm.gc.memory.promoted",
		"jvm.gc.pause",
		"jvm.memory.committed",
		"jvm.memory.max",
		"jvm.memory.used",
		"jvm.threads.daemon",
		"jvm.threads.live",
		"jvm.threads.peak",
		"jvm.threads.states",
		"logback.events",
		"process.cpu.usage",
		"process.start.time",
		"process.uptime",
		"system.cpu.count",
		"system.cpu.usage",
		"tomcat.sessions.active.current",
		"tomcat.sessions.active.max",
		"tomcat.sessions.alive.max",
		"tomcat.sessions.created",
		"tomcat.sessions.expired",
		"tomcat.sessions.rejected"
	]
}

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.

You can also create your own Actuator endpoints. In next post you will learn about the the custom actuator end points creation.

See More : Spring Boot: Custom Actuator EndPoints Creation

Conclusion

In this post you learn about these points for Spring Boot actuators:

  • Spring Boot Actuator configuration and enabling.
  • Spring Boot Actuator endpoints
  • Spring Boot actuator specific endpoints enabling for end users.
  • Spring Boot Actuator health and metrics information retrieval.

Let me know your thoughts on this post.

Happy Learning !!!

Spring Boot Main Class Configuration


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:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>             
            <configuration>    
                <mainClass>com.FacingIssuesOnIT.SpringBootMainClassApplication</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Solution 3: Specify the Main Class on run time through CLI

You can also specify the Spring Boot Main class on runtime through CLI as below:

java -cp spring-boot-app.jar -Dloader.main=com.FacingIssuesOnIT.SpringBootMainClassApplication org.springframework.boot.loader.PropertiesLauncher

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.

Let me know your thoughts on this post.

Happy Learning !!!

[Solved] Spring Boot IllegalStateException: Ambiguous mapping. Cannot map ‘XYZController’ method


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.

Let me know your thoughts on it.

Happy Learning !!!

Spring Boot Banner Customization Enable / Disable


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.

application.properties

##possible values off, console, log
spring.main.banner-mode=console

application.yml

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

Example:

${Ansi.RED}                  $$$        $$$$$      $$$$         $$$$     $$$$$
${Ansi.GREEN}                  $$$       $$$$$$$     $$$$         $$$$    $$$$$$$
${Ansi.BLUE}                  $$$       $$$$$$$     $$$$$       $$$$$    $$$$$$$
${Ansi.RED}                  $$$       $$$$$$$      $$$$       $$$$     $$$$$$$
${Ansi.GREEN}                  $$$      $$$$ $$$$     $$$$$     $$$$$    $$$$ $$$$
${Ansi.BLUE}                  $$$      $$$$ $$$$      $$$$     $$$$     $$$$ $$$$
${Ansi.RED}                  $$$     $$$$$ $$$$$     $$$$     $$$$    $$$$$ $$$$$
${Ansi.GREEN}                  $$$     $$$$   $$$$     $$$$$   $$$$$    $$$$   $$$$
${Ansi.BLUE}                  $$$     $$$$   $$$$      $$$$   $$$$     $$$$   $$$$
${Ansi.RED}                  $$$    $$$$$   $$$$$     $$$$$ $$$$$    $$$$$   $$$$$
${Ansi.GREEN}                  $$$    $$$$$$$$$$$$$      $$$$ $$$$     $$$$$$$$$$$$$
${Ansi.BLUE}          $$$$   $$$$    $$$$$$$$$$$$$      $$$$ $$$$     $$$$$$$$$$$$$
${Ansi.RED}          $$$$   $$$$   $$$$$$$$$$$$$$$      $$$$$$$     $$$$$$$$$$$$$$$
${Ansi.GREEN}          $$$$$ $$$$$   $$$$       $$$$      $$$$$$$     $$$$       $$$$
${Ansi.BLUE}          $$$$$$$$$$$  $$$$$       $$$$$     $$$$$$$    $$$$$       $$$$$
${Ansi.RED}           $$$$$$$$$   $$$$         $$$$      $$$$$     $$$$         $$$$
${Ansi.GREEN}            $$$$$$$    $$$$         $$$$      $$$$$     $$$$         $$$$

${Ansi.RED} :: Spring Boot${spring-boot.formatted-version} :: ${Ansi.DEFAULT}

Once you will run your application will show updated banner as below.

Customize Spring Boot Banner

Let me know your thoughts on it.

Happy Learning !!!

[Solved] Spring Data JPA :QueryCreationException: Could not create query for public abstract method XYZ


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.

Let me know your thoughts on it.

Happy Learning !!!

[Solved] Disable Directory Listing in Spring Boot Tomcat server for Web application


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.

<servlet>
      <servlet-name>default</servlet-name>
      <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
      <init-param>
           <param-name>debug</param-name>
           <param-value>0</param-value>
      </init-param>
      <init-param>
           <param-name>listings</param-name>
           <param-value>false</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
 </servlet>

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.

https://www.netsparker.com/blog/web-security/disable-directory-listing-web-servers/

Let us know your thought on this post.

Happy Learning !!!

Spring Boot: Common Properties and Default Value


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.

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot: Data Configuration Properties and Default Value


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.

See Also:

DAO Configuration Properties

Spring Boot load these properties in PersistenceExceptionTranslationAutoConfiguration class.

Name Default Value Description
spring.dao.exceptiontranslation.enabled true Enable the PersistenceExceptionTranslationPostProcessor.

DataSource Configuration Properties

Spring Boot load these properties in DataSourceAutoConfiguration & DataSourceProperties class.

Name Default Value Description
spring.datasource.continue-on-error false Do not stop if an error occurs while initializing the database.
spring.datasource.data Data (DML) script resource reference.
spring.datasource.data-username database usename to execute DML scripts (if different).
spring.datasource.data-password database password to execute DML scripts (if different).
spring.datasource.dbcp.* Commons DBCP specific settings
spring.datasource.dbcp2.* Commons DBCP2 specific settings
spring.datasource.driver-class-name Fully qualified JDBC driver name. if not set detect from URL by default.
spring.datasource.generate-unique-name false Generate a random datasource name.
spring.datasource.hikari.* Hikari specific settings
spring.datasource.initialize true allow to execute query using ‘data.sql’.
spring.datasource.jmx-enabled false Enable JMX support (if underlying pool provided).
spring.datasource.jndi-name JNDI location of the datasource other set fields( Class, url, username & password) are ignored when set.
spring.datasource.name testdb datasource name.
spring.datasource.password database login password.
spring.datasource.platform all Platform to use in the schema resource (schema-${platform}.sql).
spring.datasource.schema Schema (DDL) script resource reference.
spring.datasource.schema-username database user to execute DDL scripts (if different).
spring.datasource.schema-password database password to execute DDL scripts (if different).
spring.datasource.separator ; Statement separator in SQL initialization scripts.
spring.datasource.sql-script-encoding SQL scripts encoding.
spring.datasource.tomcat.* Tomcat datasource specific settings
spring.datasource.type connection pool fully qualified name implementation to use. if not set by default detected from the classpath.
spring.datasource.url JDBC database url.
spring.datasource.username database user.
spring.datasource.xa.data-source-class-name fully qualified name of XA data source.
spring.datasource.xa.properties Properties to pass to the XA data source.

JPA Configuration Properties

Spring Boot load these properties in JpaBaseConfiguration and HibernateJpaAutoConfiguration class.

Name Default Value Description
spring.data.jpa.repositories.enabled true Enable JPA repositories.
spring.jpa.database Target database to operate on. It detected by default or alternatively set using the “databasePlatform” property.
spring.jpa.database-platform Name of the target database to operate on. It detected by default or alternatively set using the “Database” enum.
spring.jpa.generate-ddl false Initialize the schema on startup.
spring.jpa.hibernate.ddl-auto DDL mode for the “hibernate.hbm2ddl.auto” property. Default value is “create-drop” when using an embedded database otherwise “none”.
spring.jpa.hibernate.naming.implicit-strategy Hibernate 5 implicit fully qualified naming strategy name .
spring.jpa.hibernate.naming.physical-strategy Hibernate 5 physical fully qualified naming strategy name .
spring.jpa.hibernate.naming.strategy Hibernate 4 fully qualified naming strategy name. Not supported with Hibernate 5.
spring.jpa.hibernate.use-new-id-generator-mappings Use Hibernate’s IdentifierGenerator for AUTO, TABLE and SEQUENCE.
spring.jpa.open-in-view true Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for request entire processing.
spring.jpa.properties.* Additional native properties set on JPA provider.
spring.jpa.show-sql false Enable SQL statements logging.

JTA Configuration Properties

Spring Boot load these properties in JtaAutoConfiguration class.

Name Default Value Description
spring.jta.enabled true Enable JTA support.
spring.jta.log-dir Transaction logs directory.
spring.jta.transaction-manager-id Transaction manager unique identifier.

Data REST Configuration Properties

Spring Boot load these properties in RepositoryRestProperties class.

Name Default Value Description
spring.data.rest.base-path Base path for Spring Data REST to repository resources.
spring.data.rest.default-page-size Default page size.
spring.data.rest.enable-enum-translation Enable enum value translation through Spring Data REST by default resource bundle.
spring.data.rest.limit-param-name URL query parameter name that decide how many results return at once.
spring.data.rest.max-page-size Maximum size of pages.
spring.data.rest.page-param-name URL query string parameter to indicates what page to return.
spring.data.rest.return-body-on-create Return a response body after creating an entity.
spring.data.rest.return-body-on-update Return a response body after updating an entity.
spring.data.rest.sort-param-name URL query string parameter to indicates what direction to sort results.

H2 Web Console Configuration Properties

Spring Boot load these properties in H2ConsoleProperties class.

Name Default Value Description
spring.h2.console.enabled false Enable the console.
spring.h2.console.path /h2-console Path at which the console will be available.
spring.h2.console.settings.trace false Enable trace output.
spring.h2.console.settings.web-allow-others false Enable remote access.

Data Redis Configuration Properties

Spring Boot load these properties in SecurityProperties class.

Name Default Value Description
spring.data.redis.repositories.enabled true Enable Redis repositories.

Redis Configuration Properties

Spring Boot load these properties in RedisProperties class.

Name Default Value Description
spring.redis.cluster.max-redirects Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes Comma-separated list of “host:port” pairs to bootstrap from.
spring.redis.database 0 Database index used by the connection factory.
spring.redis.host localhost Redis server host.
spring.redis.password Login password of the redis server.
spring.redis.pool.max-active 8 Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.pool.max-idle 8 Max number of “idle” connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.pool.max-wait -1 Maximum time a connection allocation to block before throwing an exception in case of pool is exhausted. Use -1 to block indefinitely.
spring.redis.pool.min-idle 0 Minimum number of idle connections in pool. This works only when set as positive.
spring.redis.port 6379 Redis server port.
spring.redis.sentinel.master Name of Redis server.
spring.redis.sentinel.nodes Comma-separated host:port pairs.
spring.redis.timeout 0 Connection timeout (milliseconds).

Flyway Configuration Properties

Spring Boot load these properties in FlywayProperties class.

Name Default Value Description
flyway.baseline-description
flyway.baseline-version 1 version to start migration
flyway.baseline-on-migrate
flyway.check-location false Check that migration scripts location exists.
flyway.clean-on-validation-error
flyway.enabled true Enable flyway.
flyway.encoding
flyway.ignore-failed-future-migration
flyway.init-sqls SQL statements to execute immediate to initialize when a connection obtain.
flyway.locations classpath:db/migration locations of migrations scripts
flyway.out-of-order
flyway.password JDBC password In case if you want Flyway create its own DataSource
flyway.placeholder-prefix
flyway.placeholder-replacement
flyway.placeholder-suffix
flyway.placeholders.*
flyway.schemas schemas to update
flyway.sql-migration-prefix V
flyway.sql-migration-separator
flyway.sql-migration-suffix .sql
flyway.table
flyway.url JDBC database url to migrate. Incase not set then use the primary configured data source.
flyway.user Login user of the database to migrate.
flyway.validate-on-migrate

Liquibase Configuration Properties

Spring Boot load these properties in LiquibaseProperties class.

Name Default Value Description
liquibase.change-log classpath:/db/ changelog/db.
changelog-master.yaml
Change log configuration path.
liquibase.check-change-log-location true Check the change log location exists.
liquibase.contexts Comma-separated list of runtime contexts to use.
liquibase.default-schema Default database schema.
liquibase.drop-first false Drop the database schema first.
liquibase.enabled true Enable liquibase support.
liquibase.labels Comma-separated list of runtime labels to use.
liquibase.parameters.* Change log parameters.
liquibase.password Login password of the database to migrate.
liquibase.rollback-file File to rollback SQL statements will be written when an update is performed.
liquibase.url JDBC url of the database to migrate. Incase not set then use the primary configured data source.
liquibase.user Login user of the database to migrate.

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

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.
spring.data.cassandra.connect-timeout-millis Socket option: connection time out.
spring.data.cassandra.consistency-level Queries consistency level.
spring.data.cassandra.contact-points localhost Comma-separated cluster node addresses.
spring.data.cassandra.fetch-size Queries default fetch size.
spring.data.cassandra.keyspace-name Keyspace name to use.
spring.data.cassandra.load-balancing-policy Class name of the load balancing policy.
spring.data.cassandra.port Port of the Cassandra server.
spring.data.cassandra.password Login password of the server.
spring.data.cassandra.read-timeout-millis Socket option: read time out.
spring.data.cassandra.reconnection-policy Reconnection policy class.
spring.data.cassandra.repositories.enabled Enable Cassandra repositories.
spring.data.cassandra.retry-policy Class name of the retry policy.
spring.data.cassandra.serial-consistency-level Queries serial consistency level.
spring.data.cassandra.schema-action none Schema action to take at startup.
spring.data.cassandra.ssl false Enable SSL support.
spring.data.cassandra.username Login user of the server.

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.

SOLR Configuration Properties

Spring Boot load these properties in SolrProperties class.

Name Default Value Description
spring.data.solr.host http://127.0.0.1:8983/solr Solr host. Ignored if “zk-host” is set.
spring.data.solr.repositories.enabled true Enable Solr repositories.
spring.data.solr.zk-host ZooKeeper host address i.e HOST:PORT.

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.

JEST (Elasticsearch HTTP client) Configuration Properties

Spring Boot load these properties in JestProperties class.

Name Default Value Description
spring.elasticsearch.jest.connection-timeout 3000 Connection timeout in milliseconds.
spring.elasticsearch.jest.password Login password.
spring.elasticsearch.jest.proxy.host Proxy host the HTTP client to use.
spring.elasticsearch.jest.proxy.port Proxy port the HTTP client to use.
spring.elasticsearch.jest.read-timeout 3000 Read timeout. (in milliseconds)
spring.elasticsearch.jest.uris http://localhost:9200 Comma-separated Elasticsearch instances to use.
spring.elasticsearch.jest.username Login user.

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 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.
spring.data.mongodb.username Login user of the mongo server.

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.
spring.data.neo4j.password Login password of the server.
spring.data.neo4j.repositories.enabled true Enable Neo4j repositories.
spring.data.neo4j.session.scope singleton Scope (lifetime) of the session.
spring.data.neo4j.uri URI used by the driver detected by default.
spring.data.neo4j.username Login user of the server.

JOOQ Configuration Properties

Spring Boot load these properties in JooqAutoConfiguration class.

Name Default Value Description
spring.jooq.sql-dialect Use SQLDialect JOOQ when communicating with the configured datasource. For example: `POSTGRES`

Atomikos Configuration Properties

Spring Boot load these properties in AtomikosProperties class.

Name Default Value Description
spring.jta.atomikos.connectionfactory.borrow-connection-timeout 30 Timeout for borrowing connections from the pool. (in seconds)
spring.jta.atomikos.connectionfactory.ignore-session-transacted-flag true Set to ignore the transacted flag when creating session.
spring.jta.atomikos.connectionfactory.local-transaction-mode false Set local transactions are desired.
spring.jta.atomikos.connectionfactory.maintenance-interval 60 The time between runs of the pool’s maintenance thread. (in seconds).
spring.jta.atomikos.connectionfactory.max-idle-time 60 The time after which connections are cleaned up from the pool. (in seconds)
spring.jta.atomikos.connectionfactory.max-lifetime 0 The time that a connection can be pooled for before being destroyed. 0 denotes no limit.(in seconds)
spring.jta.atomikos.connectionfactory.max-pool-size 1 The maximum pool size.
spring.jta.atomikos.connectionfactory.min-pool-size 1 The minimum pool size.
spring.jta.atomikos.connectionfactory.reap-timeout 0 The reap timeout for borrowed connections. 0 denotes no limit.( in seconds)
spring.jta.atomikos.connectionfactory.unique-resource-name jmsConnectionFactory The unique name used to identify the resource during recovery.
spring.jta.atomikos.datasource.borrow-connection-timeout 30 Timeout for borrowing connections from the pool. (in seconds)
spring.jta.atomikos.datasource.default-isolation-level Default isolation level of connections provided by the pool.
spring.jta.atomikos.datasource.login-timeout Timeout for establishing a database connection.(in seconds)
spring.jta.atomikos.datasource.maintenance-interval 60 The time between runs of the pool’s maintenance thread.(in seconds)
spring.jta.atomikos.datasource.max-idle-time 60 The time after which connections are cleaned up from the pool.(in seconds)
spring.jta.atomikos.datasource.max-lifetime 0 The time that a connection can be pooled for before being destroyed. 0 denotes no limit.(in seconds)
spring.jta.atomikos.datasource.max-pool-size 1 The maximum pool size.
spring.jta.atomikos.datasource.min-pool-size 1 The minimum pool size.
spring.jta.atomikos.datasource.reap-timeout 0 The reap timeout for borrowed connections. 0 denotes no limit.(in seconds)
spring.jta.atomikos.datasource.test-query SQL query or statement used to validate a connection before returning it.
spring.jta.atomikos.datasource.unique-resource-name dataSource The unique name used to identify the resource during recovery.
spring.jta.atomikos.properties.checkpoint-interval 500 Interval between checkpoints.
spring.jta.atomikos.properties.default-jta-timeout 10000 Default timeout for JTA transactions.
spring.jta.atomikos.properties.enable-logging true Enable disk logging.
spring.jta.atomikos.properties.force-shutdown-on-vm-exit false Specify if a VM shutdown should trigger forced shutdown of the transaction core.
spring.jta.atomikos.properties.log-base-dir Directory in which the log files should be stored.
spring.jta.atomikos.properties.log-base-name tmlog Transactions log file base name.
spring.jta.atomikos.properties.max-actives 50 Maximum active transactions.
spring.jta.atomikos.properties.max-timeout 300000 Maximum timeout that can be allowed for transactions. (in milliseconds)
spring.jta.atomikos.properties.serial-jta-transactions true Specify if sub-transactions should be joined when possible.
spring.jta.atomikos.properties.service Transaction manager implementation that should be started.
spring.jta.atomikos.properties.threaded-two-phase-commit true Use different (and concurrent) threads for two-phase commit on the resources.
spring.jta.atomikos.properties.transaction-manager-unique-name Transaction manager’s unique name.

Bironix Configuration Properties

 

Name Default Value Description
spring.jta.bitronix.connectionfactory.acquire-increment 1 Number of connections to create when pool grow.
spring.jta.bitronix.connectionfactory.acquisition-interval 1 Time to wait before trying to acquire a connection again after an invalid connection was acquired.(in second)
spring.jta.bitronix.connectionfactory.acquisition-timeout 30 Timeout for acquiring connections from the pool. (in second)
spring.jta.bitronix.connectionfactory.allow-local-transactions true Set the transaction manager should allow mixing XA and non-XA transactions.
spring.jta.bitronix.connectionfactory.apply-transaction-timeout false Set the transaction timeout should be set on the XAResource when it is enlisted.
spring.jta.bitronix.connectionfactory.automatic-enlisting-enabled true Set resources should be enlisted and delisted automatically
spring.jta.bitronix.connectionfactory.cache-producers-consumers true Set produces and consumers should be cached.
spring.jta.bitronix.connectionfactory.defer-connection-release true Set the provider can run many transactions on the same connection and supports transaction interleaving.
spring.jta.bitronix.connectionfactory.ignore-recovery-failures false Set recovery failures should be ignored.
spring.jta.bitronix.connectionfactory.max-idle-time 60 The time after which connections are cleaned up from the pool.(in second)
spring.jta.bitronix.connectionfactory.max-pool-size 10 The maximum pool size. 0 denotes no limit.
spring.jta.bitronix.connectionfactory.min-pool-size 0 The minimum pool size.
spring.jta.bitronix.connectionfactory.password The password to use to connect to the JMS provider.
spring.jta.bitronix.connectionfactory.share-transaction-connections false Set connections in the ACCESSIBLE state can be shared within the context of a transaction.
spring.jta.bitronix.connectionfactory.test-connections true Set connections should be tested when acquired from the pool.
spring.jta.bitronix.connectionfactory.two-pc-ordering-position 1 The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE).
spring.jta.bitronix.connectionfactory.unique-name jmsConnectionFactory The unique name used to identify the resource during recovery.
spring.jta.bitronix.connectionfactory.use-tm-join true Set TMJOIN should be used when starting XAResources.
spring.jta.bitronix.connectionfactory.user The user to use to connect to the JMS provider.
spring.jta.bitronix.datasource.acquire-increment 1 Number of connections to create when growing the pool.
spring.jta.bitronix.datasource.acquisition-interval 1 Time to wait before trying to acquire a connection again after an invalid connection was acquired.(in second)
spring.jta.bitronix.datasource.acquisition-timeout 30 Timeout for acquiring connections from the pool. (in second)
spring.jta.bitronix.datasource.allow-local-transactions true Set the transaction manager should allow mixing XA and non-XA transactions.
spring.jta.bitronix.datasource.apply-transaction-timeout false Set the transaction timeout should be set on the XAResource when it is enlisted.
spring.jta.bitronix.datasource.automatic-enlisting-enabled true Set resources should be enlisted and delisted automatically.
spring.jta.bitronix.datasource.cursor-holdability The default cursor holdability for connections.
spring.jta.bitronix.datasource.defer-connection-release true Set the database can run many transactions on the same connection and supports transaction interleaving.
spring.jta.bitronix.datasource.enable-jdbc4-connection-test Set Connection.isValid() is called when acquiring a connection from the pool.
spring.jta.bitronix.datasource.ignore-recovery-failures false Set recovery failures should be ignored.
spring.jta.bitronix.datasource.isolation-level The default isolation level for connections.
spring.jta.bitronix.datasource.local-auto-commit The default auto-commit mode for local transactions.
spring.jta.bitronix.datasource.login-timeout Timeout for establishing a database connection.(in second)
spring.jta.bitronix.datasource.max-idle-time 60 The time after which connections are cleaned up from the pool.(in second)
spring.jta.bitronix.datasource.max-pool-size 10 The maximum pool size. 0 denotes no limit.
spring.jta.bitronix.datasource.min-pool-size 0 The minimum pool size.
spring.jta.bitronix.datasource.prepared-statement-cache-size 0 The target size of the prepared statement cache. 0 disables the cache.
spring.jta.bitronix.datasource.share-transaction-connections false Set connections in the ACCESSIBLE state can be shared within the context of a transaction.
spring.jta.bitronix.datasource.test-query SQL query or statement used to validate a connection before returning it.
spring.jta.bitronix.datasource.two-pc-ordering-position 1 The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE).
spring.jta.bitronix.datasource.unique-name dataSource The unique name used to identify the resource during recovery.
spring.jta.bitronix.datasource.use-tm-join true Set TMJOIN should be used when starting XAResources.
spring.jta.bitronix.properties.allow-multiple-lrc false Allow multiple LRC resources to be enlisted into the same transaction.
spring.jta.bitronix.properties.asynchronous2-pc false Enable asynchronously execution of two phase commit. spring.jta.bitronix.properties.background-recovery-interval-seconds 60 Interval at which to run the recovery process in the background.(in seconds) spring.jta.bitronix.properties.current-node-only-recovery true Recover only the current node. spring.jta.bitronix.properties.debug-zero-resource-transaction false Log the creation and commit call stacks of transactions executed without a single enlisted resource. spring.jta.bitronix.properties.default-transaction-timeout 60 Default transaction timeout.(in second) spring.jta.bitronix.properties.disable-jmx false Enable JMX support. spring.jta.bitronix.properties.exception-analyzer Set the fully qualified name of the exception analyzer implementation to use. spring.jta.bitronix.properties.filter-log-status false Enable filtering of logs so that only mandatory logs are written. spring.jta.bitronix.properties.force-batching-enabled true Set if disk forces are batched. spring.jta.bitronix.properties.forced-write-enabled true Set if logs are forced to disk. spring.jta.bitronix.properties.graceful-shutdown-interval 60 Maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown time. spring.jta.bitronix.properties.jndi-transaction-synchronization-registry-name JNDI name of the TransactionSynchronizationRegistry. spring.jta.bitronix.properties.jndi-user-transaction-name JNDI name of the UserTransaction. spring.jta.bitronix.properties.journal disk Name of the journal. Can be ‘disk’, ‘null’ or a class name. spring.jta.bitronix.properties.log-part1-filename btm1.tlog Name of the first fragment of the journal. spring.jta.bitronix.properties.log-part2-filename btm2.tlog Name of the second fragment of the journal. spring.jta.bitronix.properties.max-log-size-in-mb 2 Maximum size in megabytes of the journal fragments. spring.jta.bitronix.properties.resource-configuration-filename ResourceLoader configuration file name. spring.jta.bitronix.properties.server-id ASCII ID that must uniquely identify this TM instance. Default to the machine’s IP address. spring.jta.bitronix.properties.skip-corrupted-logs false Skip corrupted transactions log entries. spring.jta.bitronix.properties.warn-about-zero-resource-transaction true Log a warning for transactions executed without a single enlisted resource.

 

Narayana Configuration Properties

Spring Boot load these properties in NarayanaProperties class.

Name Default Value Description
spring.jta.narayana.default-timeout 60 Transaction timeout.(in second)
spring.jta.narayana.expiry-scanners com.arjuna.ats.internal. arjuna.recovery. ExpiredTransactionStatusManagerScanner Comma-separated list of expiry scanners.
spring.jta.narayana.log-dir Transaction object store directory.
spring.jta.narayana.one-phase-commit true Enable one phase commit optimisation.
spring.jta.narayana.periodic-recovery-period 120 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.

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot: Security, OAUTH2 and SSO Configuration Properties and Default Value


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.

See Also:

Security Configuration Properties

Spring Boot load these properties in SecurityProperties class.

Name Default Value Description
security.basic.authorize-mode role Security authorize mode to apply.
security.basic.enabled true Enable basic authentication.
security.basic.path /** Comma-separated paths to secure.
security.basic.realm Spring HTTP basic realm name.
security.enable-csrf false Enable Cross Site Request Forgery support.
security.filter-order 0 Security filter chain order.
security.filter-dispatcher-types ASYNC, FORWARD, INCLUDE, REQUEST Security filter chain dispatcher types.
security.headers.cache true Enable cache control HTTP headers.
security.headers.content-type true Enable “X-Content-Type-Options” header.
security.headers.frame true Enable “X-Frame-Options” header.
security.headers.hsts Set HSTS (HTTP Strict Transport Security) as (none, domain, all).
security.headers.xss true Enable cross site scripting (XSS) protection.
security.ignored Comma-separated paths to exclude from the default secured paths.
security.require-ssl false Enable secure channel for all requests.
security.sessions stateless Session creation policy (always, never, if_required, stateless).
security.user.name user Default user name.
security.user.password Password for the default user name. A random password for default logged on.
security.user.role USER Granted roles for the default user name.

Security OAUTH2 Configuration Properties

Spring Boot load these properties in OAuth2ClientProperties class.

Name Default Value Description
security.oauth2.client.client-id OAuth2 client id.
security.oauth2.client.client-secret OAuth2 client secret. A random secret is generated by default

Security OAUTH2 SSO Properties

Spring Boot load these properties in OAuth2SsoProperties class.

Name Default Value Description
security.oauth2.sso.filter-order Filter order if not providing an explicit WebSecurityConfigurerAdapter
security.oauth2.sso.login-path /login Path to the login page,that will redirect to the OAuth2 Authorization

Security OAUTH2 Resources Properties

Spring Boot load these properties in ResourceServerProperties class.

Name Default Value Description
security.oauth2.resource.id Identifier of the resource.
security.oauth2.resource.jwt.key-uri The URI of the JWT token. It can set when value is not available and the key is public.
security.oauth2.resource.jwt.key-value The verification key of the JWT token. Can either be a symmetric secret or PEM-encoded RSA public key.
security.oauth2.resource.prefer-token-info true Use the token info, it can be set to false when the user info.
security.oauth2.resource.service-id resource
security.oauth2.resource.token-info-uri URI of the token decoding endpoint.
security.oauth2.resource.token-type Send token type when using the userInfoUri.
security.oauth2.resource.user-info-uri URI of the user endpoint.

 

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot: Integration Platform Properties and Default Value


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.

See Also:

ActiveMQ Configuration Properties

Spring Boot load these properties in ActiveMQProperties class.

Name Default Value Description
spring.activemq.broker-url URL of the ActiveMQ broker.For Default instance `tcp://localhost:61616`
spring.activemq.in-memory true Required if the default broker URL should be in memory. Ignored if an explicit brokerspecified.
spring.activemq.password Login password of the broker.
spring.activemq.user Login user of the broker.
spring.activemq.packages.trust-all false Trust all packages.
spring.activemq.packages.trusted Comma-separated packages to trust use when not trusting all packages.
spring.activemq.pool.configuration.* See PooledConnectionFactory.
spring.activemq.pool.enabled false Set when PooledConnectionFactory need to create instead of a regular ConnectionFactory.
spring.activemq.pool.expiry-timeout 0 Connection expiration timeout.(millieconds)
spring.activemq.pool.idle-timeout 30000 Connection idle timeout. (millieconds)
spring.activemq.pool.max-connections 1 Maximum number of pooled connections.

ARTEMIS Configuration Properties

Spring Boot load these properties in ArtemisProperties class.

Name Default Value Description
spring.artemis.embedded.cluster-password Cluster password. Randomly generated on startup by default.
spring.artemis.embedded.data-directory Journal file directory. Not necessary if persistence is turned off.
spring.artemis.embedded.enabled true Enable embedded mode, In case Artemis server APIs are available.
spring.artemis.embedded.persistent false Enable persistent store.
spring.artemis.embedded.queues Comma-separated queues to create on startup.
spring.artemis.embedded.server-id Server id. By default, an auto-incremented counter is used.
spring.artemis.embedded.topics Comma-separated topics to create on startup.
spring.artemis.host localhost Artemis broker host.
spring.artemis.mode Artemis deployment mode, auto-detected by default.
spring.artemis.password Login password of the broker.
spring.artemis.port 61616 Artemis broker port.
spring.artemis.user Login user of the broker.

Spring Batch Configuration Properties

Spring Boot load these properties in BatchProperties class.

Name Default Value Description
spring.batch.initializer.enabled Create the required batch tables on startup if needed. Enabled automatically, if custom schema is configured or no custom table prefix is set.
spring.batch.job.enabled true Execute all Spring Batch jobs on context startup.
spring.batch.job.names Comma-separated job names to execute on startup. By default, all Jobs in the context are executed.
spring.batch.schema classpath:org/
springframework/batch
/core/schema
-@@platform@@.sql
SQL file path to use to initialize the database schema.
spring.batch.table-prefix Table prefix for all batch meta-data tables.

HornetQ Configuration Properties

Spring Boot load these properties in HornetQProperties class.

Name Default Value Description
spring.hornetq.embedded.cluster-password Cluster password. Randomly generated on startup by default.
spring.hornetq.embedded.data-directory Journal file directory. Not necessary if persistence is turned off.
spring.hornetq.embedded.enabled true Enable embedded mode In case HornetQ server APIs are available.
spring.hornetq.embedded.persistent false Enable persistent store.
spring.hornetq.embedded.queues Comma-separated queues to create on startup.
spring.hornetq.embedded.server-id Server id. By default, an auto-incremented counter is used.
spring.hornetq.embedded.topics Comma-separated topics to create on startup.
spring.hornetq.host localhost HornetQ broker host.
spring.hornetq.mode HornetQ deployment mode, auto-detected by default.
spring.hornetq.password Login password of the broker.
spring.hornetq.port 5445 HornetQ broker port.
spring.hornetq.user Login user of the broker.

JMS Configuration Properties

Spring Boot load these properties in JmsProperties class.

Name Default Value Description
spring.jms.jndi-name Connection factory JNDI name. When configured, take precedence from others connection factory auto-configurations.
spring.jms.listener.acknowledge-mode Acknowledge mode for conainer. By default, the listener transcted to automatic acknowledgment.
spring.jms.listener.auto-startup true Start the container automatically on startup.
spring.jms.listener.concurrency Minimum number of concurrent consumers.
spring.jms.listener.max-concurrency Maximum number of concurrent consumers.
spring.jms.pub-sub-domain false Specify if the default destination type is topic.

Rabbit Configuration Properties

Spring Boot load these properties in RabbitProperties class.

Name Default Value Description
spring.rabbitmq.addresses Comma-separated addresses to which the client should connect.
spring.rabbitmq.cache.channel.checkout-timeout Waiting time to obtain a channel In case cache size has been reached.(in Millisecond)
spring.rabbitmq.cache.channel.size Number of channels to retain in the cache.
spring.rabbitmq.cache.connection.mode CHANNEL Connection factory cache mode.
spring.rabbitmq.cache.connection.size Number of connections to cache.
spring.rabbitmq.connection-timeout Connection timeout, in milliseconds; zero for infinite.
spring.rabbitmq.dynamic true Create an AmqpAdmin bean.
spring.rabbitmq.host localhost RabbitMQ host.
spring.rabbitmq.listener.acknowledge-mode Acknowledge mode of container
spring.rabbitmq.listener.auto-startup true Start the container automatically on startup.
spring.rabbitmq.listener.concurrency Minimum number of consumers.
spring.rabbitmq.listener.default-requeue-rejected Default true. Set to requeue delivery failures.
spring.rabbitmq.listener.max-concurrency Maximum number of consumers.
spring.rabbitmq.listener.prefetch Number of messages handled in a single request. For good performance, It should be greater than or equal to the transaction size (if configured).
spring.rabbitmq.listener.retry.enabled false Whether or not publishing retries are enabled.
spring.rabbitmq.listener.retry.initial-interval 1000 Interval between the two subsquent attempt to deliver a message.
spring.rabbitmq.listener.retry.max-attempts 3 Maximum attempts to deliver a message.
spring.rabbitmq.listener.retry.max-interval 10000 Maximum interval between attempts.
spring.rabbitmq.listener.retry.multiplier 1.0 Muliplier apply on previous delivery retry interval.
spring.rabbitmq.listener.retry.stateless true Whether or not retry is stateless or stateful.
spring.rabbitmq.listener.transaction-size Number of messages processed in each transaction. For good performnace, it should be less than or equal to the prefetch count.
spring.rabbitmq.password Login to authenticate against the broker.
spring.rabbitmq.port 5672 RabbitMQ port.
spring.rabbitmq.publisher-confirms false Enable publisher confirms.
spring.rabbitmq.publisher-returns false Enable publisher returns.
spring.rabbitmq.requested-heartbeat Requested heartbeat timeout, in seconds; zero for none.
spring.rabbitmq.ssl.enabled false Enable SSL support.
spring.rabbitmq.ssl.key-store key store path that holds the SSL certificate.
spring.rabbitmq.ssl.key-store-password Password used to access the key store.
spring.rabbitmq.ssl.trust-store Trust store that holds SSL certificates.
spring.rabbitmq.ssl.trust-store-password Password used to access the trust store.
spring.rabbitmq.ssl.algorithm SSL algorithm to use. By default configure by the rabbit client library.
spring.rabbitmq.template.mandatory false Enable mandatory messages.
spring.rabbitmq.template.receive-timeout 0 Timeout for `receive()` methods.
spring.rabbitmq.template.reply-timeout 5000 Timeout for `sendAndReceive()` methods.
spring.rabbitmq.template.retry.enabled false Set to true, for enable retries in the `RabbitTemplate`.
spring.rabbitmq.template.retry.initial-interval 1000 Interval between two subsquent attempt to publish a message.
spring.rabbitmq.template.retry.max-attempts 3 Maximum attempts to publish a message.
spring.rabbitmq.template.retry.max-interval 10000 Maximum attempts to publish a message.
spring.rabbitmq.template.retry.multiplier 1.0 Multiplier apply on previous publishing retry interval.
spring.rabbitmq.username Login user to authenticate broker.
spring.rabbitmq.virtual-host Virtual host to while connecting to the broker.

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot: DevTools Properties and Default Value


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.

See Also:

DevTools Configuration Properties

Spring Boot load these properties in DevToolsProperties class.

Name Default Value Description
spring.devtools.livereload.enabled true Enable a livereload.com compatible server.
spring.devtools.livereload.port 35729 Server port.
spring.devtools.restart.additional-exclude Additional patterns excluded from triggering a full restart.
spring.devtools.restart.additional-paths Additional paths to watch for changes.
spring.devtools.restart.enabled true Enable automatic restart.
spring.devtools.restart.exclude META-INF/maven/**,
META-INF/resources/**,
resources/**,static/**,
public/**,templates/**,
**/*Test.class,
**/*Tests.class,
git.properties
File System Patterns that excluded from triggering a full restart.
spring.devtools.restart.poll-interval 1000 Amount of waiting time between polling for classpath changes.(in milliseconds)
spring.devtools.restart.quiet-period 400 Amount of quiet time required before a restart is triggered without classpath changes . (in milliseconds)
spring.devtools.restart.trigger-file Name of file, if any class path file change will trigger the restart. If not specified file n classpath change will trigger the restart.

Remote DevTools Configuration Properties

Spring Boot load these properties in RemoteDevToolsProperties class.

Name Default Value Description
spring.devtools.remote.context-path /.~~spring-boot!~ Context path used to handle the remote connection.
spring.devtools.remote.debug.enabled true Enable remote debug support.
spring.devtools.remote.debug.local-port 8000 Local remote debug server port.
spring.devtools.remote.proxy.host Proxy host to remote application connection
spring.devtools.remote.proxy.port Proxy port to remote application connection.
spring.devtools.remote.restart.enabled true Enable remote restart.
spring.devtools.remote.secret It’s required property,to shared secret to establish a connection
spring.devtools.remote.secret-header-name X-AUTH-TOKEN HTTP header used to transfer the shared secret.

 

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot: Web Application Properties and Default Values


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.

See Also:

Embedded Server Configuration Properties

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.
server.tomcat.accesslog.request-attributes-enabled false Set request attributes for IP address, ptotocol, port and Hostname.
server.tomcat.accesslog.suffix .log Log file name suffix.
server.tomcat.background-processor-delay 30 Delay between the invocation of backgroundProcess methods.(seconds)
server.tomcat.basedir Tomcat base directory. If not set then temporary directory will be used.
server.tomcat.internal-proxies 10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\
192\\.168\\.\\d{1,3}\\.\\d{1,3}|\\
169\\.254\\.\\d{1,3}\\.\\d{1,3}|\\
127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\
172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\
172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\
172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}
regular expression matching trusted IP addresses.
server.tomcat.max-threads 0 Maximum amount of worker threads.
server.tomcat.min-spare-threads 0 Minimum amount of worker threads.
server.tomcat.port-header X-Forwarded-Port HTTP header name used to override the original port value.
server.tomcat.protocol-header Header value holds the incoming protocol, usually named “X-Forwarded-Proto”.
server.tomcat.protocol-header-https-value https Param Value in header that indicates that the incoming request uses SSL.
server.tomcat.remote-ip-header http header param from which the remote ip is extracted. For instance `X-FORWARDED-FOR`
server.tomcat.uri-encoding UTF-8 Character encoding to use to decode the URI.
server.undertow.accesslog.dir Undertow access log directory.
server.undertow.accesslog.enabled false Enable access log.
server.undertow.accesslog.pattern common Format pattern for access logs.
server.undertow.accesslog.prefix access_log. Log file name prefix.
server.undertow.accesslog.suffix log Log file name suffix.
server.undertow.buffer-size Each buffer size in bytes.
server.undertow.buffers-per-region Number of buffer for per region.
server.undertow.direct-buffers Allocate buffers space outside the Java heap.
server.undertow.io-threads Number of worker threads create for I/O.
server.undertow.worker-threads Number of worker threads.

Freemarker Properties

Spring Boot load these properties in FreeMarkerAutoConfiguration

Name Default Value Description
spring.freemarker.allow-request-override false HttpServletRequest attributes of same name are allowed to override controller generated model attributes.
spring.freemarker.allow-session-override false Enable HttpSession attributes of same name are allowed to override controller generated model attributes.
spring.freemarker.cache false Enable template caching
spring.freemarker.charset UTF-8 Template encoding.
spring.freemarker.check-template-location true Check that the templates location exists.
spring.freemarker.content-type text/html Content-Type value.
spring.freemarker.enabled true Enable MVC view resolution for this technology.
spring.freemarker.expose-request-attributes false Enable all request attributes should be added to the model prior to merging with the template.
spring.freemarker.expose-session-attributes false Enable all HttpSession attributes should be added with model prior to merging with the template.
spring.freemarker.expose-spring-macro-helpers true Enable expose a RequestContext for use by Spring’s macro library, under the name “springMacroRequestContext”.
spring.freemarker.prefer-file-system-access true Enable hot detection of template changes from file system.
spring.freemarker.prefix Prefix prepended with view names when building a URL.
spring.freemarker.request-context-attribute Name of the RequestContext attribute that will apply on all views.
spring.freemarker.settings.* Well-known FreeMarker keys that will passed to FreeMarker’s Configuration.
spring.freemarker.suffix Suffix appended with view names when building a URL.
spring.freemarker.template-loader-path classpath:/templates/ Comma-separated template paths.
spring.freemarker.view-names White list of view names.

Groovy Template Properties

Spring Boot load these properties in GroovyTemplateAutoConfiguration

Name Default Value Description
spring.groovy.template.allow-request-override false HttpServletRequest attributes of same name are allowed to override controller generated model attributes.
spring.groovy.template.allow-session-override false HttpSession attributes of same name are allowed to override (hide) controller generated model attributes..
spring.groovy.template.cache Enable template caching.
spring.groovy.template.charset UTF-8 Template encoding.
spring.groovy.template.check-template-location true Check that the templates location exists.
spring.groovy.template.configuration.* See GroovyMarkupConfigurer
spring.groovy.template.content-type test/html Content-Type value.
spring.groovy.template.enabled true Enable MVC view resolution for this technology.
spring.groovy.template.expose-request-attributes false Enable All request attributes added with model prior to merging with the template.
spring.groovy.template.expose-session-attributes false Enable All HttpSession attributes added with model prior to merging with the template.
spring.groovy.template.expose-spring-macro-helpers true Enable expose a RequestContext for use by Spring’s macro library, under the name “springMacroRequestContext”.
spring.groovy.template.prefix Prefix prepended with view names when building a URL.
spring.groovy.template.request-context-attribute Name of the RequestContext attribute for all views.
spring.groovy.template.resource-loader-path classpath:/templates/ Template path.
spring.groovy.template.suffix .tpl Suffix appended with view names when building a URL.
spring.groovy.template.view-names White list of view names.

Spring HATEOAS Properties

Spring Boot load these properties in HateoasProperties

Name Default Value Description
spring.hateoas.use-hal-as-default-json-media-type true Enable application/hal+json mime type responses for requests that accept application/json.

HTTP Message Conversion Properties

Name Default Value Description
spring.http.converters.preferred-json-mapper jackson Preferred JSON mapper for HTTP message conversion. Specified “gson” in case jacson and gson both are on the classpath.

HTTP Encoding Properties

Spring Boot load these properties in HttpEncodingProperties class.

Name Default Value Description
spring.http.encoding.charset UTF-8 Charset of HTTP requests and responses. Added to the “Content-Type” header.
spring.http.encoding.enabled true Enable http encoding.
spring.http.encoding.force Force the encoding on HTTP requests and responses.
spring.http.encoding.force-request Force the encoding on HTTP requests. Defaults to true.
spring.http.encoding.force-response Force the encoding on HTTP responses.
spring.http.encoding.mapping Locale to Encoding mapping.

Multipart Properties

Spring Boot load these properties in MultipartProperties class.

Name Default Value Description
spring.http.multipart.enabled true Enable support of multi-part uploads.
spring.http.multipart.file-size-threshold 0 Threshold after which files will be written to disk.Suffixed “MB” or “KB”.
spring.http.multipart.location Intermediate location of uploaded files.
spring.http.multipart.max-file-size 1Mb Max file size. Suffixed “MB” or “KB”.
spring.http.multipart.max-request-size 10Mb Max request size. Suffixed “MB” or “KB”.
spring.http.multipart.resolve-lazily false Set to resolve the multipart request lazily when file or parameter access.

Jackson Properties

Spring Boot load these properties in JacksonProperties class.

Name Default Value Description
spring.jackson.date-format Date format or a fully-qualified date format class name. For example `yyyy-MM-dd HH:mm:ss`.
spring.jackson.default-property-inclusion Controls the properties inclusion during serialization.
spring.jackson.deserialization.* on/off features for Jackson that affect the way Java objects are deserialized.
spring.jackson.generator.* on/off features for Jackson generators.
spring.jackson.joda-date-time-format Joda date time strig format. If it is configured with a format string use it otherwise will use “date-format” as a fallback .
spring.jackson.locale Locale used for formatting.
spring.jackson.mapper.* on/off features of Jackson general features.
spring.jackson.parser.* on/off features for Jackson parsers.
spring.jackson.property-naming-strategy Set Jackson’s PropertyNamingStrategy type sub class as a fully-qualified class name.
spring.jackson.serialization.* on/off features of Jackson that affect the way Java objects are serialized.
spring.jackson.serialization-inclusion Controls the properties inclusion during serialization by configuring values in Jackson’s JsonInclude.Include enumeration.
spring.jackson.time-zone Time zone for date. For example `America/Los_Angeles`

Jersey Properties

Spring Boot load these properties in JerseyProperties class.

Name Default Value Description
spring.jersey.application-path base URI path for the application that override the value of “@ApplicationPath” if specified.
spring.jersey.filter.order 0 Jersey filter chain order.
spring.jersey.init.* Init parameters to pass to Jersey through servlet or filter.
spring.jersey.servlet.load-on-startup -1 Load on startup priority of the Jersey servlet.
spring.jersey.type servlet Jersey integration type.

Spring Mobile Device Views Properties

Spring Boot load these properties in DeviceDelegatingViewResolverAutoConfiguration class.

Name Default Value Description
spring.mobile.devicedelegatingviewresolver.enable-fallback false Enable support for fallback resolution.
spring.mobile.devicedelegatingviewresolver.enabled false Enable device view resolver.
spring.mobile.devicedelegatingviewresolver.mobile-prefix mobile/ Prefix prepended to view names of mobile devices.
spring.mobile.devicedelegatingviewresolver.mobile-suffix Suffix appended to view names of mobile devices.
spring.mobile.devicedelegatingviewresolver.normal-prefix Prefix prepended to view names of normal devices.
spring.mobile.devicedelegatingviewresolver.normal-suffix Suffix appended to view names of normal devices.
spring.mobile.devicedelegatingviewresolver.tablet-prefix tablet/ Prefix prepended to view names of tablet devices.
spring.mobile.devicedelegatingviewresolver.tablet-suffix Suffix appended to view names of tablet devices.

Spring Mobile Site Preference Properties

Spring Boot load these properties in SitePreferenceAutoConfiguration class.

Name Default Value Description
spring.mobile.sitepreference.enabled true Enable SitePreferenceHandler.

Mustache Templates Properties

Spring Boot load these properties in MustacheAutoConfiguration class.

Name Default Value Description
spring.mustache.allow-request-override HttpServletRequest attributes with same name are allowed to override controller generated model attributes..
spring.mustache.allow-session-override HttpSession attributes with same name are allowed to override controller generated model attributes.
spring.mustache.cache Enable template caching.
spring.mustache.charset Template encoding.
spring.mustache.check-template-location Check that the templates location exists.
spring.mustache.content-type Content-Type value.
spring.mustache.enabled Enable MVC view resolution for this technology.
spring.mustache.expose-request-attributes All request attributes added to the model prior to merging with the template.
spring.mustache.expose-session-attributes All HttpSession attributes added to the model prior to merging with the template.
spring.mustache.expose-spring-macro-helpers Expose a RequestContext use Spring’s macro library, under the name “springMacroRequestContext”.
spring.mustache.prefix classpath:/templates/ Prefix to template names.
spring.mustache.request-context-attribute RequestContext attribute name for all views.
spring.mustache.suffix .html Suffix to template names.
spring.mustache.view-names White list of view names.

Spring MVC Properties

Spring Boot load these properties in WebMvcProperties class.

Name Default Value Description
spring.mvc.async.request-timeout Amount of time before asynchronous request handling times out.(in milliseconds)
spring.mvc.date-format Date format For example `dd/MM/yyyy`.
spring.mvc.dispatch-trace-request false Dispatch TRACE requests to the FrameworkServlet doService method.
spring.mvc.dispatch-options-request true Dispatch OPTIONS requests to the FrameworkServlet doService method.
spring.mvc.favicon.enabled true Enable resolution of favicon.ico.
spring.mvc.formcontent.putfilter.enabled true Enable Spring’s HttpPutFormContentFilter.
spring.mvc.ignore-default-model-on-redirect true Content of the “default” model need to ignored during redirect scenarios.
spring.mvc.locale Set Locale otherwise By default locale is overridden by the “Accept-Language” header.
spring.mvc.locale-resolver accept-header Define how locale should be resolved.
spring.mvc.log-resolved-exception false Enable warn logging, for exceptions resolved by a “HandlerExceptionResolver”.
spring.mvc.media-types.* Maps file extensions for content negotiation.
spring.mvc.message-codes-resolver-format Formatting strategy for message codes. For example `PREFIX_ERROR_CODE`.
spring.mvc.servlet.load-on-startup -1 Load on startup priority for Spring Web Services servlet.
spring.mvc.static-path-pattern /** Path pattern used for static resources.
spring.mvc.throw-exception-if-no-handler-found false If a “NoHandlerFoundException”, then throw if no Handler was found to process a request.
spring.mvc.view.prefix Prefix for Spring MVC view.
spring.mvc.view.suffix Suffux for Spring MVC view.

Spring Resources Handling Properties

Spring Boot load these properties in ResourceProperties class.

.

Name Default Value Description
spring.resources.add-mappings true Enable default resource handling.
spring.resources.cache-period Cache period (in seconds)for the resources served by the resource handler.
spring.resources.chain.cache true Enable caching in the Resource chain.
spring.resources.chain.enabled Enable the Spring Resource Handling chain. By default disabled as long as one strategy has been enabled.
spring.resources.chain.gzipped false Enable resolution of already gzipped resources.
spring.resources.chain.html-application-cache false Enable HTML5 application cache manifest rewriting.
spring.resources.chain.strategy.content.enabled false Enable the content for Version Strategy.
spring.resources.chain.strategy.content.paths /** Comma-separated list of patterns for Version Strategy.
spring.resources.chain.strategy.fixed.enabled false Enable the fixed Version Strategy.
spring.resources.chain.strategy.fixed.paths /** Comma-separated list of patterns for Version Strategy.
spring.resources.chain.strategy.fixed.version Version string for Version Strategy.
spring.resources.static-locations classpath:/META-INF/resources/, classpath:/resources/,
classpath:/static/,
classpath:/public/
Locations of static resources

Spring Session Properties

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.
spring.session.jdbc.schema classpath:
org/springframework/
session/jdbc/
schema-@@platform
@@.sql
SQL file Path for initialize the database schema.
spring.session.jdbc.table-name SPRING_SESSION Name of database table used to store sessions.
spring.session.mongo.collection-name sessions Collection name used to store sessions.
spring.session.redis.flush-mode Flush mode for the Redis sessions.
spring.session.redis.namespace Namespace for keys used to store sessions.
spring.session.store-type Session store type.

Spring Social Properties

Spring Boot load these properties in SocialWebAutoConfiguration class.

Name Default Value Description
spring.social.auto-connection-views false Enable the connection status for supported providers.

Spring Social Facebook Properties

Spring Boot load these properties in FacebookAutoConfiguration class.

Name Default Value Description
spring.social.facebook.app-id Your Facebook App ID
spring.social.facebook.app-secret Your Facebook App Secret

Spring Social LinkedIn Properties

Spring Boot load these properties in LinkedInAutoConfiguration class.

Name Default Value Description
spring.social.linkedin.app-id Your LinkedIn App ID
spring.social.linkedin.app-secret Your LinkedIn App Secret

Spring Local Twitter Properties

Spring Boot load these properties in TwitterAutoConfiguration class.

Name Default Value Description
spring.social.twitter.app-id Your Twitter App ID
spring.social.twitter.app-secret Your Twitter App Secret

Thymeleaf Properties

Spring Boot load these properties in ThymeleafAutoConfiguration class.

Name Default Value Description
spring.thymeleaf.cache true Enable template caching.
spring.thymeleaf.check-template true Check that the template exists..
spring.thymeleaf.check-template-location true Check that the templates location.
spring.thymeleaf.content-type text/html Content-Type value.
spring.thymeleaf.enabled true Enable MVC Thymeleaf view resolution.
spring.thymeleaf.encoding UTF-8 Template encoding.
spring.thymeleaf.excluded-view-names Comma-separated list of view names that can excluded from resolution.
spring.thymeleaf.mode HTML5 Template mode to be applied to templates. Refer StandardTemplateModeHandlers.
spring.thymeleaf.prefix classpath:/templates/ Prefix prepended to view names for building a URL.
spring.thymeleaf.suffix .html Suffix appended to view names for building a URL.
spring.thymeleaf.template-resolver-order template resolver order in chain.
spring.thymeleaf.view-names Comma-separated list of view names.

Velocity Templates Properties

Spring Boot load these properties in VelocityAutoConfiguration class.

Name Default Value Description
spring.velocity.allow-request-override false HttpServletRequest attributes with same name are allowed to override controller generated model attributes.
spring.velocity.allow-session-override false HttpSession attributes with same name are allowed to override controller generated model attributes.
spring.velocity.cache Enable template caching.
spring.velocity.charset UTF-8 Template encoding.
spring.velocity.check-template-location true Check that the templates location exists.
spring.velocity.content-type text/html Content-Type value.
spring.velocity.date-tool-attribute Name of the DateTool helper object to expose in the Velocity context of the view.
spring.velocity.enabled true Enable MVC view resolution for this technology.
spring.velocity.expose-request-attributes false all request attributes should be added to the model prior to merging with the template.
spring.velocity.expose-session-attributes false all HttpSession attributes should be added to the model prior to merging with the template.
spring.velocity.expose-spring-macro-helpers true expose a RequestContext for use by Spring’s macro library, under the name “springMacroRequestContext”.
spring.velocity.number-tool-attribute Name of the NumberTool helper object to expose in the Velocity context of the view.
spring.velocity.prefer-file-system-access true Prefer file system access for template loading for hot detection of template changes.
spring.velocity.prefix Prefix prepended to view names for building a URL.
spring.velocity.properties.* Additional velocity properties.
spring.velocity.request-context-attribute Name of the RequestContext attribute for all views.
spring.velocity.resource-loader-path classpath:/templates/ Template path.
spring.velocity.suffix .vm Suffix appended to view names for building a URL.
spring.velocity.toolbox-config-location Velocity Toolbox config location. For instance `/WEB-INF/toolbox.xml`
spring.velocity.view-names White list of view names.

Spring Web Service Properties

Spring Boot load these properties in WebServicesProperties class.

Name Default Value Description
spring.webservices.path /services Path that serves as the base URI.
spring.webservices.servlet.init Servlet init parameters Spring for Sevices.
spring.webservices.servlet.load-on-startup -1 Load on startup priority for Spring Web Services servlet.

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot: Core Common Properties and Default Value


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.

See Also:

Banner Properties

Name Default Value Description
banner.charset UTF-8 Banner file encoding.
banner.location classpath:banner.txt Banner file location.
banner.image.location classpath:banner.gif Banner image file location, also use jpg/png.
banner.image.width 76 Width of the banner image in chars.
banner.image.height Height of the banner image in chars.
banner.image.margin 2 Left hand image margin in chars.
banner.image.invert false 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)
spring.sendgrid.username SendGrid account username
spring.sendgrid.password SendGrid account password
spring.sendgrid.proxy.host SendGrid proxy host
spring.sendgrid.proxy.port SendGrid proxy

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Spring Boot Maven Application


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.

  1. Check Java Version
  2. Check Maven Version
  3. Create Application in Maven
  4. Add Spring Boot Parent
  5. Add spring-boot-stater-
  6. Add Business Functionality
  7. 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.

Java Version

If you are not getting version as above in screen then follow steps in this link: Setup Java/JDK and Eclipse On Window & Linux

Check Maven Version

You can run command mvn -version to get the current Maven version installed in your machine.

Maven Version

If you are not getting version as above in screen then follow steps in this link: Configure Maven in Window and Linux?

Create Application in Maven

To Create a Maven-based Web application, go to the directory where you want to create an application run below maven command.


mvn archetype:generate -DgroupId=com.fiot  -DartifactId=SpringBootMavenApp -DarchetypeArtifactId=maven-archetype-quickstart  -DinteractiveMode=false

Create Maven Application

It will create a java maven application with the below directory structure.


SpringBootMavenApp
-src
--main
---java
----com
-----fiot
------App.java
--test
---java
----com
-----fiot
------AppTest.java
-pom.xml

Add spring-boot-stater

Added highlighted lines of the statement in pom.xml to make your application Spring Boot Web Application.

Spring Boot Maven POM

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.

Also See: Spring Boot Starters List

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!”.

package com.fiot;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class App
{
	@RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

}

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.

To run your application use below command.


java -jar ./target/SpringBootMavenApp-1.0-SNAPSHOT.jar

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 Starters


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.

In our previous article, Spring Boot Maven Application has used two Spring Boot starters as given below:

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.


 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
    </parent>

See Also: spring-boot-starter-parent in Detail.

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.


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

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 System Requirements and Compatibility


Spring Boot required the below configuration for developing an application.

JDK Version Range

Although, Spring Boot Application can be developed with Java 6 or 7 but most recommended to use Java 8 if possible.

  • Spring Framework 5.3.x: JDK 8 to JDK 17 (expected)
  • Spring Framework 5.2.x: JDK 8 to JDK 15 (expected)
  • Spring Framework 5.1.x: JDK 8 to JDK 12
  • Spring Framework 5.0.x: JDK 8 to JDK 10
  • Spring Framework 4.3.x: JDK 6 to JDK 8

Build Tool

You can choose either build tool Maven or Gradle for developed Spring Boot Java Applications.

  • Maven 3.2+
  • Gradle [2.9, 3.x]

Servlet Containers

Spring Boot application can be deployed on any compatible servlet containers 3.0+. Here is a list of supported embedded servlet containers:

Server Name Servlet Version Java Version
Tomcat 8 3.1 Java 7+
Tomcat 7 3.0 Java 6+
Jetty 9.3 3.1 Java 8+
Jetty 9.2 3.1 Java 7+
Jetty 8 3.0 Java 6+
Undertow 1.3 3.1 Java 7+

IDE

Although Spring Boot application can be developed on IDE like NetBeans, Eclipse, etc. but most recommended IDE is STS (Spring Tool Suite).

Spring Boot Overview


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)
  • Written in Java
  • Website: https://spring.io/

Spring Boot Advantages

  • Spring Boot Create stand-alone Spring applications that can be started using uber jar i.e java -jar.
  • Spring Boot embed Tomcat, Jetty or Undertow directly. You don’t need to deploy WAR files explicitly
  • Spring Boot provides featured ‘starter’ POMs to simplify your Maven configuration.
  • Spring Boot automatically configures Spring dependencies whenever possible.
  • Spring Boot provides production-ready non-functional features (metrics, health checks, security and externalized configuration) by the actuator.
  • Spring Boot required no XML configuration and also not generate any code.

Spring Boot Features

  • Spring Application
  • Web Development
  • Application Events and Features
  • Externalized Configuration
  • Properties Files
  • YAML support
  • Type-safe Configuration
  • Logging
  • Security
  • Admin Features

Spring Boot Version

  • Spring Boot 0.9 Release in 2002
  • Spring Boot 1.0 Release in 2003
  • Spring Boot 2.0 Release in 2006
  • Spring Boot 3.0 Release in 2009
  • Spring Boot 4.0 Release in 2013
  • Spring Boot 5.0 Release in 2017
  • Spring Boot 5.2.4 Release on February 25, 2020