Spring Profiles

Spring profiles allow you to configure different parts of your application based on the environment it is running in. This can be useful for things like configuring different database connections for development and production environments, or enabling different features based on whether the application is running in a test environment.

Here’s an example of how to use Spring profiles in a Spring Boot application:

In your application.properties, define the different profiles that you will use in your application. For example:

spring.profiles.active=dev

Create a application-dev.properties file in the same directory as your application.properties file. This file will contain properties specific to the dev profile. For example:

spring.datasource.url=jdbc:mysql://localhost:3306/dev_db
spring.datasource.username=dev_user
spring.datasource.password=dev_password

Create a application-prod.properties file in the same directory as your application.properties file. This file will contain properties specific to the prod profile. For example:

spring.datasource.url=jdbc:mysql://prod-db:3306/prod_db
spring.datasource.username=prod_user
spring.datasource.password=prod_password

Now you can use the spring.profiles.active property to control which profile is active at runtime. For example, if you want to run your application with the prod profile, you can use JVM system parameter(-Dspring.profiles.active) like the below:

$ java -jar -Dspring.profiles.active=prod myapp.jar

Profiles can also be activated via the environment variable:

export spring_profiles_active=prod

You can also use the @Profile annotation to define beans that should only be activated for certain profiles. For example:

@Configuration
public class ProfileConfig {

    @Bean
    @Profile("dev")
    public DataSource devDataSource() {
        // configure dev data source
    }

    @Bean
    @Profile("prod")
    public DataSource prodDataSource() {
        // configure prod data source
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *