How to set a Spring Boot property with an underscore in its name via Environment Variables?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Spring Boot is a widely-used framework for developing Java applications, especially for implementing RESTful services. A common requirement while configuring Spring Boot applications is to set properties via environment variables, especially in cloud-native or containerized environments. One may encounter challenges when dealing with property names that include underscores.
Understanding Spring Boot Property Configuration
Spring Boot allows you to configure properties using several methods, such as application properties/yaml files, system properties, command-line arguments, and environment variables. Environment variables are particularly useful in cloud environments like Kubernetes or when using Docker.
To set a Spring Boot property via environment variables, name the environment variable in a specific way. Spring Boot automatically maps these variables to properties by converting their names:
- Periods `.` in property names are replaced by underscores `_`.
- Property names are made uppercase.
For example, to set a property `spring.datasource.url`, the corresponding environment variable would be `SPRING_DATASOURCE_URL`.
Handling Underscores in Property Names
Sometimes the property name itself might contain underscores. In such cases, the transformation rules still apply, but it can lead to confusion in configuration, especially when underscores are legitimate parts of the property name and not just delimiters.
Example Scenario
Suppose you want to configure a custom property named `my.custom_property`. When setting this property via an environment variable, you need to follow these conventions:
- Convert your property name to uppercase.
- Replace any periods in the property name with underscores.
Hence, `my.custom_property` becomes `MY_CUSTOM_PROPERTY`.
Implementing and Testing in Spring Boot
Below is a basic example demonstrating how you can apply this configuration in a Spring Boot application:
- Naming Conventions: Always convert your property to uppercase and replace periods with underscores.
- Avoid Ambiguity: Ensure that legitimate underscores in your property names do not get misinterpreted.
- Check for Overrides: Verify that properties set by different configuration sources (e.g., YAML files, command-line arguments) don’t inadvertently override each other.
- Cross-Platform Compatibility: On some systems, the sensitivity to case may vary, so always use uppercase for environment variable names.

