Configuration: Properties and Profiles

Configuration: Properties and Profiles in Java: Your database URL differs between your laptop, the test server, and production.

Concept Explanation

Your database URL differs between your laptop, the test server, and production. Hard-coding it means rebuilding the application for each environment. Spring Boot externalises configuration so one artifact runs everywhere.


Reading Properties

application.properties:

app.name=Shop API
app.max-items=50
spring.datasource.url=jdbc:mysql://localhost:3306/shop

Inject a single value:

@Value("${app.max-items}")
private int maxItems;

Better — bind a whole group to a typed object:

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private String name;
    private int maxItems;
    // getters and setters required for binding
}

This is validated at startup rather than failing at first use, and gives you IDE autocomplete.


Profiles

Keep one file per environment:

application.properties         <- shared defaults
application-dev.properties     <- laptop
application-prod.properties    <- production

Activate one:

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

Profile-specific beans:

@Bean
@Profile("dev")
public DataSource h2InMemory() { ... }

@Bean
@Profile("prod")
public DataSource productionPool() { ... }

Precedence (highest wins)

  1. Command-line arguments
  2. Environment variables
  3. application-{profile}.properties
  4. application.properties
  5. @Value defaults in code

This ordering is what lets a container platform override any setting without touching your jar.


Secrets

Never commit passwords. Read them from the environment:

spring.datasource.password=${DB_PASSWORD}

Spring resolves DB_PASSWORD from the environment, so the value never enters source control.


Common Mistakes

  1. Committing production secrets: Once pushed, treat the credential as compromised and rotate it.
  2. Typos in property names: A misspelled key is silently ignored. @ConfigurationProperties catches this; @Value does not.
  3. @Value on a static field: Silently stays null. Spring injects instance fields only.
  4. Forgetting to activate a profile: Without it, only application.properties applies — often pointing at localhost.

Best Practices

  • Prefer @ConfigurationProperties over scattered @Value annotations.
  • Secrets from the environment or a vault, never from files in the repository.
  • Keep defaults safe: If a profile is missing, the app should fail loudly rather than quietly hit production.

Practice Exercises

  1. The Two Profiles: Create dev and prod property files with different app.name values, then start the app under each and print the active one.
  2. The Typed Binding: Convert three @Value fields into a single @ConfigurationProperties class.
  3. The Override Chain: Set the same property in the file, an environment variable, and a command-line argument. Confirm which wins.