Skip to main content

Application Properties And Environment Profiling In Spring Boot

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.

 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:

  1.  application-dev.properties 
  2.  application-test.properties 
  3.  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!

Popular posts from this blog

How to Implement AWS RDS Database IAM Authentication in Spring Boot

Amazon RDS for MySQL allows authentication using AWS Identity and Access Management (IAM) database authentication. With this authentication method, you don't need to use a password when you connect to a DB instance. Instead, you use an authentication token. Let us understand how this works? An authentication token is a unique string of characters that Amazon RDS generates on request. Authentication tokens are generated using AWS Signature Version 4. Each token has a lifetime of 15 minutes. You don't need to store user credentials in the database, because authentication is managed externally using IAM. You can also still use standard database authentication. Since IAM authentication tokens are short-lived access tokens that are valid for 15 minutes. For the RDS database this token works as a database password that is required to establish a connection and does not determine how long the existing connection can last. The default value for connection to be alive without activit

How to upload files in Amazon S3 Bucket using Spring Boot

As stated in the title, we are going to demonstrate that how we can upload and retrieve files from the amazon s3 bucket in spring boot. For this, we must have an account on amazon web services (AWS) . And the next thing you need to have is an IAM user that has programmatic access to the s3 bucket. Follow the steps below to create an IAM user and s3 bucket. Table of Contents 1. Steps to create an IAM user in AWS with S3 bucket full access permission Step 1.1 Login to your AWS account   Step 1.2 Set the user details Step 1.3 Set user permissions Step 1.4 Create a user group and set the access policy Step 1.5 Add user to the group Step 1.6  Set the tags (optional) Step 1.7  Review the user details and permission summary Step 1.8 Download the user credentials 2. See, how to create s3 bucket. Step 2.1 Click on the "Create bucket" button. Step 2.2 Enter the bucket name and select bucket region. Step 2.3 Set file accessibility for bucket items as public/private

What Is SSL Certificate and how it works?

Deep Dive into SSL Certificate What Is an SSL Certificate? SSL (Secure Sockets Layer) is the common name for TLS (Transport Layer Security), a security protocol that enables encrypted communications between two machines. An SSL certificate is a small data file leveraging this security protocol to serve two functions: Authentication – SSL certificates serve as credentials to authenticate the identity of a website. They are issued to a specific domain name and web server after a Certificate Authority, also known as a Certification Authority (CA), performs a strict vetting process on the organization requesting the certificate. Depending on the certificate type, it can provide information about a business or website's identity and authenticate that the website is a legitimate business. Secure data communication - When SSL is installed on a web server, it enables the padlock to appear in the web browser. It activates the HTTPS protocol and creates a secure connection between th

How to Implement Spring Security in Spring Boot

Security Example in Spring Boot Implementation of Spring Security in the Spring Boot application is the key point to learn for spring boot developers. Because Authentication and Authorization are the backbones of the whole application. Getting started with the Spring Security Series, this is the first part, in this article we are going to focus on the authentication part with minimal registration. The implementation of registration flow with email verification, customizing password encoding, and setting up password strengths and rules will be explored in another separate article for each.  This article will be the base of the spring security series, the other security features will be explained on the basis of this implementation, so be focused and let's understand. The code contains proper naming & brief comments that makes it very comprehensive. If you feel any difficulty or find any issue, please drop a comment below this post The main goal of this article is to impleme

Custom Pagination with search and filters in Spring Boot

Every spring boot application is made to manage a large set of data. Also, we need to perform a search and filter the data according to need, And also we cannot load all data in one go on a single page so we need pagination too. In this article, we are going to demonstrate custom pagination with search and filter performed through ajax call. Goal: This demonstration is performed on a set of students' data. We have written a method to generate sample data.   Table of Contents 1. Initialize the project with the following dependencies 2. Set the application properties 3. Create the Student entity 4. Enum to denote the class of student 5. Create JPA repository of entity 6. Create the search & filter command object (CO) 7. Create a data transfer object (DTO) of the Entity for returning the response 8. Create a service for implementing the business login 9. Create a controller 10. Create a utility class for date conversions 11. Create the HTML Data Table design 12.

Maven or Gradle - built tool selection in Spring Boot

  Spring Boot -Selection of built tool Gradle Gradle is an open-source build automation tool that is designed to be flexible enough to build almost any type of software, It is fully open source and similar to Maven and Ant. But Gradle has taken advantage of both Maven and Ant and also it has removed the disadvantages of Maven and Ant and created as a first-class built tool. It uses domain-specific language based on the programming language Groovy , differentiating it from Apache Maven, which uses XML for its project configuration. Gradle allows to create or customize built procedure and we can create an additional task with groovy scripts that can be executed before/after built. It also determines the order of tasks run by using a directed acyclic graph . Several developers created Gradle and first released in 2007, and in 2013, it was adopted by Google as the build system for Android projects. It was designed to support multi-project builds that are expected to