In Spring Boot, managing application properties is crucial for configuring the application based on different environments (e.g., development, testing, production). Spring Boot provides a feature called Profiles to help with this. Profiles allow you to define different sets of properties for various environments and switch between them easily. This makes it straightforward to maintain environment-specific configurations without modifying the codebase of the Spring Boot application.
Managing Application Properties with Profiles in Spring Boot
Spring Boot Profiles are a powerful feature that helps you manage different configurations for different environments (e.g., development, testing, production) in a Spring Boot application. Using profiles lets you maintain environment-specific settings without changing the application's codebase. This makes it easier to deploy the application across various environments with appropriate configurations.
Profiles Overview
In Spring Boot, a profile is essentially a named set of configuration properties. Each profile can include different settings for various aspects of the application, such as data sources, security configurations, and other environment-specific properties. Profiles allow you to modularize configuration, ensuring that only the relevant properties are loaded based on the active profile.
How Profiles Work
Define the Profiles:
We can create separate property files for each profile. For example, you might have application-dev.properties
for the development environment and application-prod.properties
for production. These files contain profile-specific properties.
Default Properties:
The application.properties
file contains the default properties that apply to all profiles unless overridden by a specific profile.
src/main/resources/application.properties
# Common properties
spring.application.name=MyApp
server.port=8080
Development Profile:
Create the properties file for the development profile. This file will override the properties in application.properties
when the dev
profile is active.
src/main/resources/application-dev.properties
# Development-specific properties
spring.datasource.url=jdbc:h2:mem:devdb
spring.datasource.username=devuser
spring.datasource.password=devpass
logging.level.org.springframework=DEBUG
Production Profile
Similarly, create the properties file for the production profile.
src/main/resources/application-prod.properties
# Production-specific properties
spring.datasource.url=jdbc:mysql://prodserver/mydb
spring.datasource.username=produser
spring.datasource.password=prodpass
logging.level.org.springframework=ERROR
2. Activate the Profiles
To use a specific profile, you need to activate it. Spring Boot provides several methods to activate profiles, including command-line arguments, environment variables, and default settings in configuration files.
- Command-Line Arguments: When running the Spring Boot application, you can specify the active profile with the
--spring.profiles.active
argument.
java -jar myapp.jar --spring.profiles.active=dev
- Environment Variables: You can set the environment variable
SPRING_PROFILES_ACTIVE
to specify the active profile.
export SPRING_PROFILES_ACTIVE=prod
- Default Profile in Configuration Files: You can specify the default profile in the
application.properties
, which will be used if no other profiles are activated.
spring.profiles.active=dev
Profile Precedence
If multiple profiles are active, Spring Boot follows a specific order to determine which properties take precedence. Profiles can be layered, allowing you to define base properties in the default file and override them with profile-specific properties.
- Properties in the
application-{profile}.properties
files, where {profile}
is the active profile. - Properties in the
application.properties
or application.yml
. - Properties defined programmatically or through other sources.
Benefits of Managing Application Properties with Profiles in Spring Boot
- Environment-Specific Configurations: Allows seamless management of environment-specific settings.
- Modularization: Profiles help in modularizing configuration files, making them easier to manage.
- Ease of Deployment: Simplifies the deployment process by ensuring the correct configuration is applied in each environment.
Implementation: Managing Application Properties with Profiles in Spring Boot
Step 1: Create a New Spring Boot Project
Create a new Spring Boot Project using IntelliJ IDEA. Choose the following options:
- Name:
profiles-demo
- Language: Java
- Type: Maven
- Packaging: Jar
Click on the Next button.
Step 2: Add Dependencies
Add the following dependencies into the Spring Boot Project.
Project Structure
Once the project is created, the file structure should look like this:
Step 3: Configure Default Application Properties
# src/main/resources/application.properties
# Basic application properties
spring.application.name=ProfileExampleApp
server.port=8080
# Default database configuration (overridden by profile-specific properties)
spring.datasource.url=jdbc:h2:mem:defaultdb
spring.datasource.username=defaultuser
spring.datasource.password=defaultpass
# Default profile to be active
spring.profiles.active=test
This file contains common properties applicable to all profiles unless overridden. It also sets the default active profile to test
.
Step 4: Configure Dev Application Properties
# src/main/resources/application-dev.properties
# Development environment database configuration
spring.datasource.url=jdbc:h2:mem:devdb
spring.datasource.username=devuser
spring.datasource.password=devpass
# Development-specific logging level
logging.level.com.example=DEBUG
This file contains properties specific to the development environment, such as the database connection and logging level.
Step 5: Configure Prod Application Properties
# src/main/resources/application-prod.properties
# Production environment database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/proddb
spring.datasource.username=produser
spring.datasource.password=prodpass
# Hibernate DDL setting for production
spring.jpa.hibernate.ddl-auto=update
# Production-specific logging level
logging.level.com.example=ERROR
This file contains properties specific to the production environment, including database connection settings and Hibernate configuration.
Step 6: Configure Test Application Properties
# src/main/resources/application-test.properties
# Test environment database configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=testuser
spring.datasource.password=testpass
# Test-specific logging level
logging.level.com.example=TRACE
This file contains properties specific to the testing environment, including the database connection and a more verbose logging level for detailed testing.
Step 7: Create the DataSourceService Class
Java
package com.gfg.profilesdemo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class DataSourceService {
// Injecting the data source URL from the active profile
@Value("${spring.datasource.url}")
private String datasourceUrl;
// Injecting the data source username from the active profile
@Value("${spring.datasource.username}")
private String datasourceUsername;
// Injecting the data source password from the active profile
@Value("${spring.datasource.password}")
private String datasourcePassword;
// Method to print the data source properties to the console
public void printDataSourceProperties() {
System.out.println("Datasource URL: " + datasourceUrl);
System.out.println("Datasource Username: " + datasourceUsername);
System.out.println("Datasource Password: " + datasourcePassword);
}
}
This service class retrieves and prints the data source properties from the active profile. It uses Spring's @Value
annotation to inject the properties from the configuration files.
Step 8: Create the DataSourceController Class
Java
package com.gfg.profilesdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/datasource")
public class DataSourceController {
// Injecting the DataSourceService
@Autowired
private DataSourceService dataSourceService;
// Endpoint to print the data source properties
@GetMapping("/properties")
public String getDataSourceProperties() {
dataSourceService.printDataSourceProperties();
return "Check the console for data source properties";
}
}
This controller class exposes a REST API endpoint (/api/datasource/properties
) that triggers the DataSourceService
to print the data source properties to the console. It uses Spring's @RestController
and @RequestMapping
annotations.
Step 9: Main class
This is the entry point of the application. No changes are required in the Main class.
Java
package com.gfg.profilesdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProfilesDemoApplication {
public static void main(String[] args) {
// Starting the Spring Boot application
SpringApplication.run(ProfilesDemoApplication.class, args);
}
}
pom.xml file:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>profiles-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>profiles-demo</name>
<description>profiles-demo</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 10: Run the Application
Run the application using the command below:
mvn spring-boot:run
Output:
Step 11: Testing the Endpoint
Access the endpoint to verify the profile-based configuration:
GET http://localhost:8080/api/datasource/properties
Output:
Default Profile Properties
Change the Profile to Dev
Again the run the endpoint,
GET http://localhost:8080/api/datasource/properties
In Application logs, we will see the Dev profile properties
Change the Profile to Prod
Again the run the endpoint,
GET http://localhost:8080/api/datasource/properties
In Application logs, we will see the Prod profile properties
Change the Profile to Test
Again the run the endpoint,
GET http://localhost:8080/api/datasource/properties
In Application logs, we will see the Test profile properties
By following these steps, we can effectively manage the application properties for the different environments using the Spring Boot profiles. This approach keeps the configurations organized and environment-specific, enhancing the maintainability and flexibility.
Similar Reads
Configuring Spring Boot Applications with Maven Profiles In a software development environment, applications must often be configured differently for various environments such as development, testing, and production. Managing these configurations can be challenging, but Maven provides powerful features called profiles to handle this. Maven profiles allow
5 min read
Spring Boot - Application Properties Spring Boot is built on top of the Spring Framework and includes all its features while simplifying configuration and setup. It has become a favorite among developers because it provides a rapid, production-ready environment that allows them to focus on business logic instead of dealing with complex
3 min read
Add Build Properties to a Spring Boot Application Spring Boot framework is an open-source framework for developing web applications with high performance and the Spring Boot makes it much easier to develop Spring-based applications developed by Java programming In this article, we will learn how to add build properties to a Spring Boot Application.
4 min read
How to Access Values From application.properties in Spring Boot? In a Spring Boot application, application.properties is the central repository for defining configuration properties. These properties are accessible across the application to customize behavior. Accessing values from application.properties is a common requirement in Spring Boot projects. Spring Boo
3 min read
Changing Spring Boot Properties at Runtime Spring Boot provides a flexible way to configure application properties, typically defined statically in the application.properties or application.yml files. However, there are scenarios where properties need to be changed dynamically at runtime without restarting the application. In this article, w
5 min read
Managing Configuration for Microservices with Spring Cloud Config Spring Cloud Config provides the centralized external configuration management system and it is designed to work well with modern microservices architectures. It is the part of larger Spring Config suite of the tools that aim to help the developers built the cloud-native applications. Spring Cloud C
4 min read