Environment variables let you set values outside your code. This helps keep your app flexible and secure.
Environment variables in configuration in Spring Boot
spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}Use ${VARIABLE_NAME} to refer to environment variables in application.properties or application.yml.
If the environment variable is missing, Spring Boot may fail to start or use a default if provided.
spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}:8080 to provide a default value if PORT is not set.server.port=${PORT:8080}app.name=${APP_NAME:MyApp}This Spring Boot app reads an environment variable APP_GREETING to show a greeting message. If the variable is not set, it shows 'Hello, World!'.
Run the app and visit /greet to see the message.
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class ConfigController { @Value("${APP_GREETING:Hello, World!}") private String greeting; @GetMapping("/greet") public String greet() { return greeting; } }
Environment variables are case-sensitive on most systems.
Use application.yml for cleaner configuration if preferred.
Remember to set environment variables before starting your Spring Boot app.
Environment variables let you configure apps without changing code.
Use ${VAR_NAME} syntax in Spring Boot config files.
You can provide default values with : after the variable name.