javabeginner

Spring Boot — Profiles and Configuration

Manage environment-specific config with Spring profiles: application-{env}.yml, @Profile, and @Value.

java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;

// application.yml
// spring:
//   profiles:
//     active: dev
//
// application-dev.yml
// app:
//   db-url: jdbc:h2:mem:testdb
//   cache-enabled: false
//   log-level: DEBUG
//
// application-prod.yml
// app:
//   db-url: ${DATABASE_URL}
//   cache-enabled: true
//   log-level: WARN

// Configuration class
@Configuration
public class AppProperties {
    @Value("${app.db-url}")
    private String dbUrl;

    @Value("${app.cache-enabled:false}")
    private boolean cacheEnabled;

    @Value("${app.log-level:INFO}")
    private String logLevel;

    @Value("${app.api-key:#{null}}")
    private String apiKey;

    // Getters
    public String getDbUrl() { return dbUrl; }
    public boolean isCacheEnabled() { return cacheEnabled; }
    public String getLogLevel() { return logLevel; }
}

// Profile-specific beans
@Configuration
class DataSourceConfig {

    @Bean
    @Profile("dev")
    DataSource devDataSource() {
        System.out.println("Using H2 in-memory database");
        return createDataSource("jdbc:h2:mem:testdb");
    }

    @Bean
    @Profile("prod")
    DataSource prodDataSource(@Value("${app.db-url}") String url) {
        System.out.println("Using production database");
        return createDataSource(url);
    }

    @Bean
    @Profile("!prod")
    Object devToolsConfig() {
        // Only active when NOT in prod
        System.out.println("Dev tools enabled");
        return new Object();
    }

    private DataSource createDataSource(String url) {
        return null; // placeholder
    }
}

// Service with profile logic
@Service
class NotificationService {
    @Value("${spring.profiles.active:default}")
    private String activeProfile;

    public void send(String message) {
        if ("prod".equals(activeProfile)) {
            System.out.println("Sending real notification: " + message);
        } else {
            System.out.println("[DEV] Would send: " + message);
        }
    }
}

// Run with: java -jar app.jar --spring.profiles.active=prod
// Or: SPRING_PROFILES_ACTIVE=prod java -jar app.jar

interface DataSource {}

Sponsored

Railway

Use Cases

  • Environment-specific application configuration
  • Conditional bean creation per environment
  • Feature toggles based on deployment target

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.