🌱 What are Spring Profiles?

Spring Profiles allow you to define different configurations for different environments β€” like dev, test, or prod.

πŸ” Instead of changing code every time you deploy, you create separate config files, and Spring Boot automatically picks the right one.

πŸ’‘ Real-Life Example

You might want:

  • Local DB for development
  • MySQL for production
  • H2 for testing

Using profiles, you can define different properties for each case.

πŸ›  How to Create Profiles

1. Create property files:

application-dev.properties Β 
application-test.properties Β 
application-prod.properties

2. In each file, define environment-specific values:

Example application-dev.properties:

server.port=8081
spring.datasource.url=jdbc:h2:mem:testdb

Example application-prod.properties:

server.port=8080
spring.datasource.url=jdbc:mysql://prod-db-url

πŸš€ Activate a Profile

βœ… Method 1: In application.properties

spring.profiles.active=dev

βœ… Method 2: As a Command Line Argument


java -jar app.jar --spring.profiles.active=prod

βœ… Method 3: In application.yml

spring:
Β  profiles:
Β  Β  active: test

πŸ§ͺ Use Profile in Code

You can also use profiles in Java code using @Profile:

@Profile("dev")
@Component
public class DevDataLoader implements CommandLineRunner {
Β  Β  public void run(String... args) {
Β  Β  Β  Β  System.out.println("Loading dev data...");
Β  Β  }
}

βœ… Benefits of Spring Profiles

  • Clean separation of configs
  • Easy to switch environments
  • No need to change code between dev/test/prod
  • Helpful in CI/CD and Docker setups

Back to blog

Leave a comment