Spring Boot @Profile Example

1. Introduction

The @Profile annotation in Spring Boot is used to define which components should be registered based on the active application profiles. This feature is crucial for maintaining different configurations for various environments, such as development, testing, and production, without changing the code.

Key Points

1. @Profile specifies the environment under which a bean should be included in the application context.

2. Multiple profiles can be activated simultaneously, allowing for complex configuration scenarios.

3. Profiles can be specified in application properties or programmatically set.

2. Development Steps

1. Create a configuration class with beans specific to different profiles.

2. Use the @Profile annotation to designate which profiles each configuration applies to.

3. Activate profiles through application properties or command line.

3. Implementation Example

// Step 1: Define configuration classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
public class AppConfiguration {

    @Bean
    @Profile("dev")
    public String devDatabaseConnection() {
        return "Development Database Connection";
    }

    @Bean
    @Profile("test")
    public String testDatabaseConnection() {
        return "Test Database Connection";
    }

    @Bean
    @Profile("prod")
    public String prodDatabaseConnection() {
        return "Production Database Connection";
    }
}

// Step 2: Set active profile in `application.properties`
# Active profiles
spring.profiles.active=dev,test

// Step 3: Alternatively, activate profiles via command line
# Command to run Spring Boot application with specific profiles
java -jar myapplication.jar --spring.profiles.active=dev,test

Explanation:

1. AppConfiguration contains methods annotated with @Profile. Each method defines a bean that is only loaded into the Spring Context when its corresponding profile is active. For example, devDatabaseConnection is only available when the 'dev' profile is active.

2. The @Profile("dev"), @Profile("test"), and @Profile("prod") annotations ensure that beans are conditionally loaded based on the active profiles, allowing for targeted functionality in different environments.

3. Profiles can be activated in application.properties by setting spring.profiles.active to the desired profiles, or they can be activated via the command line when starting the application. This flexibility allows developers and operations teams to adapt the application behavior without changing the codebase.

Comments