Introduction

Spring Boot profiles are a powerful feature for managing configurations in different environments. They allow you to define multiple sets of configurations and activate the appropriate profile based on your application's runtime environment. In this guide, we'll explore how to use Spring Boot profiles with sample code.


Prerequisites

Before you start, make sure you have the following prerequisites:


Defining Profiles

You can define profiles in your application properties or YAML files. Profiles are a way to group configurations for specific environments or use cases. For example:

# application.yml
# Common Configuration
spring:
datasource:
url: jdbc:mysql://localhost:3306/commondb
username: commonuser
password: commonpass
# Development Profile
---
spring:
profiles: development
datasource:
url: jdbc:mysql://localhost:3306/devdb
username: devuser
password: devpass
# Production Profile
---
spring:
profiles: production
datasource:
url: jdbc:mysql://localhost:3306/proddb
username: produser
password: prodpass

In this example, we have a common configuration and separate configurations for development and production profiles. The profiles are defined using the "---" syntax in YAML files.


Activating Profiles

You can activate a profile using the spring.profiles.active property in your application properties or YAML file. For example:

# application.properties
# Activate the "development" profile
spring.profiles.active=development

By setting spring.profiles.active to "development," the application will use the configurations defined under the "Development Profile" in the YAML file.


Using Profiles in Code

You can use profiles in your Spring Boot application code to conditionally execute code blocks based on the active profile. Here's an example:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Value("${spring.datasource.url}")
private String databaseUrl;
public String getDatabaseInfo() {
return "Database URL: " + databaseUrl;
}
}

In this code, the value of the "databaseUrl" property is determined by the active profile. If the "development" profile is active, it will use the development database URL.


Conclusion

Spring Boot profiles are a valuable tool for managing configurations in different environments. They help you maintain a consistent application codebase while allowing you to adapt to various runtime conditions. By understanding and using profiles effectively, you can simplify the management of your Spring Boot applications.