Application Properties
As we know Spring Boot configures almost all the configurations automatically, it also enables us to customize the configurations and properties according to our needs and environment. There are various methods which we can use to do the same.
We can either write all properties in a textual file, do programmatically in our Java classes, or can set it while starting the application through CLI by passing command-line arguments.
By default, Spring Initializr creates an application.properties file inside the project's class path. But we can also define it in the YAML file.
Know the differences between the .properties file and .yml file
The properties that we are talking about are database credentials and URL, server port, logging file path, catch control variables, can write any custom string constants, etc.
Table of Contents
Method 1: Using application.properties
Sample of application.properties file
spring.datasource.url=jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=false
spring.datasource.username=root
spring.datasource.password=demo
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
server.port=8089
#custom constant
file.upload.location=/home/ubuntu/uploads/
Method 2: Using application.yml file
YAML is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The SpringApplication
class automatically supports YAML as an alternative to properties whenever you have the SnakeYAML library on your classpath.
Sample of application.yml file
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=false
username: root
password: demo
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: false
server:
port: 8089
Method 3: Using the Java class
Setting up the application properties from the Java classes is up to you that how you like to do, you may do it through making a component and assign all the properties in beans. Components are executed at first priority while starting the web applications.
Sample of Class file
@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {
private String host;
private int port;
private String from;
private List<String> defaultRecipients;
private Map<String, String> additionalHeaders;
private Credentials credentials;
//...
// standard getters and setters
}
Method 4: Using command-line arguments
This method applies after building the application jar. While running the jar from CLI write all the properties to the JSON format as shown below example
$ java -jar myapp.jar --spring.application.json='{"server.port":8084,"spring.jpa.show-sql":true}'
How many properties do we need to write in an application?
There are lots of properties that you can write inside your application.properties
file, inside your application.yml
file, or as command-line switches. It does not have any number, it depends upon your customization, and dependencies included in your application. Almost all the properties have a default value preset by the auto-configure feature of the spring boot. The number of dependencies you add the number of properties increases. Also, you can define your own properties.
In Spring Boot official documentation the list common application properties are described.
Spring Boot Profiling
What Are Profiles in Spring Boot?
Every enterprise application has many environments, like:
Dev | Test | Stage | Prod | UAT / Pre-Prod
Each environment requires a setting that is specific to them. For example, in DEV, we do not need to constantly check database consistency. Whereas in TEST and STAGE, we need to. These environments host specific configurations called Profiles.
How do we maintain profiles?
This is simple — properties files!
We make properties files for each environment and set the profile in the application accordingly, so it will pick the respective properties file. Don't worry, we will see how to set it up.
This article will demonstrate how to setup Profiles for your Spring Boot application.
Let's start with setting up a Spring Boot application from the Spring Starter.
Next, we need to import the project into your favorite IDE(I am using Intellij Idea here) as a Gradle Project. Below is the project structure:
In this demo application, we will see how to configure different databases at runtime based on the specific environment by their respective profiles.
As the DB connection is better to be kept in a property file, it remains external to an application and can be changed. We will do so here. But, Spring Boot — by default — provides just one property file ( application.properties
). So, how will we segregate the properties based on the environment?
The solution would be to create more property files and add the "profile" name as the suffix and configure Spring Boot to pick the appropriate properties based on the profile.
Then, we need to create three application.properties
:
-
application-dev.properties
-
application-test.properties
-
application-prod.properties
Of course, the application.properties
will remain as a master properties file, but if we override any key in the profile-specific file, the latter will gain precedence.
I will now define DB configuration properties for in respective properties file and add code in DBConfiguration.class
to pick the appropriate settings.
Here is the base application.properties
:
spring.profiles.active=dev
spring.application.name=Profiles
app.message=This is the primary Application Property for ${spring.application.name}
In DEV application-dev.properties
, we will use an in-memory database:
#DEV ENVIRONEMNT SETTING#
app.message= This is the property file for the ${spring.application.name} specific to DEV Environment
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
In TEST application-test.properties
, we will be using a lower instance of RDS MySQL database:
#TEST ENVIRONEMNT SETTING#
app.message= This is the property file for the ${spring.application.name} specific to TEST Environment
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql-instance1.sovanmaws.us-east-1.rds.amazonaws.com:3306/profiles
spring.datasource.username=<USERNAME>
spring.datasource.password=<SECRET>
And in PROD application-prod.properties
, we will use a higher instance of the MySQL database. (It's the price that matters...)
#PROD ENVIRONEMNT SETTING#
app.message= This is the property file for the ${spring.application.name} specific to PRODUCTION Environment!! Be ALERT!!
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql-instance100.sovanmaws.us-east-1.rds.amazonaws.com:3306/profiles
spring.datasource.username=<USERNAME_PROD>
spring.datasource.password=<SECRET_PASS>
Now, we are done with properties files. Let's configure in the ProfileSpecificMethods.class
to pick the correct one.
package com.lkvcodestudio.profiling.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@ConfigurationProperties("spring.datasource")
public class ProfileSpecificMethods {
private String driverClassName;
private String url;
private String username;
private String password;
@Profile("dev")
@Bean
public String devDatabaseConnection() {
System.out.println("DB connection for DEV - H2");
System.out.println(driverClassName);
System.out.println(url);
return "DB connection for DEV - H2";
}
@Profile("test")
@Bean
public String testDatabaseConnection() {
System.out.println("DB Connection to RDS_TEST - Low Cost Instance");
System.out.println(driverClassName);
System.out.println(url);
return "DB Connection to RDS_TEST - Low Cost Instance";
}
@Profile("prod")
@Bean
public String prodDatabaseConnection() {
System.out.println("DB Connection to RDS_PROD - High Performance Instance");
System.out.println(driverClassName);
System.out.println(url);
return "DB Connection to RDS_PROD - High Performance Instance";
}
//getters and setters
}
We have used the @Profile("Dev")
to let the system know that this is the BEAN
that should be picked up when we set the application profile to DEV. The other two beans will not be created at all.
One last setting is how to let the system know that this is DEV, TEST, or PROD. But, how do we do this?
We will use the application.properties
to use the key below:
spring.profiles.active=dev
From here, Spring Boot will know which profile to pick. Let's run the application now!
With the profile in DEV mode, and it should pick H2 DB.
Now, change the profile to PROD. We will see MySQL with High Config for DB. This should be picked, and the message will be overridden with the PROD message.
That's it! We just have to change it once in the application.properties
to let Spring Boot know which environment the code is deployed in, and it will do the magic with the setting.
Please please comment below to get github source code link!