Customizing using Spring Boot properties

Spring Boot allows you to customize your application configurations and you can use the same application code in different environments such as staging, production, and so on. Spring Boot provides several methods for this customization—you can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.

Spring Boot gives you a free hand to override auto-configuration using a lot of Spring Boot properties. So that you can easily override these properties. Let's see how to override the values of these Spring Boot properties using the application.properties file. By default, Spring Boot looks for application.properties in these locations (in this order):

  • The /config sub-directory of the working directory
  • The working directory
  • The config package in the classpath
  • The classpath root

You can create a PropertySource based on these files. There are many, many configuration properties available in Spring Boot.

Let's see the following configuration example of the DataSource bean. In this example, we will see how to control or override Spring Boot's default configuration of the DataSource bean in the Spring application. There are the following typical customizations:

  • Use the predefined properties
  • Change the underlying data source connection pool implementation
  • Define your own DataSource bean

Let's see the following common properties configurable from the properties file; first, we have to override the DataSource bean configuration:

# Connection settings 
 
spring.datasource.url=  
spring.datasource.username= 
spring.datasource.password= 
spring.datasource.driver-class-name= 
 
# SQL scripts to execute 
 
spring.datasource.schema=  
spring.datasource.data= 
 
# Connection pool settings 
 
spring.datasource.initial-size=  
spring.datasource.max-active= 
spring.datasource.max-idle= 
spring.datasource.min-idle=

As you can see, you have to define your setting for the DataSource bean definition, such as Connection settings, SQL scripts to execute, and Connection pool settings. But Spring Boot creates a pooled DataSource bean by default if a known pool dependency is available. The spring-boot-starter-jdbc or spring-boot-starter-jpa Starter pulls in the tomcat-jdbc connection pool by default. But you can override this to use alternatives—Tomcat, HikariCP, and Commons DBCP 1 and 2.

Let's see another example for web container configuration using Spring Boot properties. Here's the configuration code:

server.port=9000 
server.address=192.168.11.21 
server.session-timeout=1800 
server.context-path=/accounts 
server.servlet-path=/admin 
 

Let's see how to override auto-configuration in the Spring Boot application by replacing generated beans in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset