Spring Boot configuration: where values come from and how to bind them
A Spring Boot application reads every setting from one Environment built from many sources. This page shows the order of those sources running, binds values with @Value and with @ConfigurationProperties records, and covers environment variables, YAML, imports, validation and the mistakes that silently bind nothing.
Contents
How Spring Boot assembles its configuration Which value wins, shown running @Value: one value, with defaults and SpEL @ConfigurationProperties: typed groups of settings Environment variables and relaxed binding YAML files and spring.config.import Validating settings at startup Traps that bind nothing Choosing how to configure
How Spring Boot assembles its configuration
Every value a Spring Boot application reads, from server.portapp.max-retriesEnvironment
Spring Boot fills that list before any of your beans exist. It adds command-line arguments, Java system properties, operating system environment variables and the JSON in SPRING_APPLICATION_JSONapplication.propertiesapplication.yaml
| Source | Typical use |
|---|---|
Default properties (SpringApplication.setDefaultProperties | Fallbacks set in code |
@PropertySource | Loading an extra file in plain Spring style |
Config data: application.properties.yaml | The application's normal settings |
| OS environment variables | Containers, Kubernetes, CI pipelines |
Java system properties (-Dkey=value | JVM launch scripts |
SPRING_APPLICATION_JSON | Many settings in one environment variable |
Command-line arguments (--key=value | One-off overrides |
Test properties (@SpringBootTest(properties = ...)@TestPropertySource | Tests |
Reading the values is the second half. @Value("${key}")@ConfigurationProperties10sDuration5MBDataSize
The programs on this page run Spring Boot 4.1.2 without a web server. Each one writes its configuration files into a temporary folder and puts that folder on the classpath through a URLClassLoadersrc/main/resources-parameters
Which value wins, shown running
The key app.greeting
package props.precedence;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.env.PropertySource;
@SpringBootApplication
public class PropertyPrecedence {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
app.greeting=from application.properties
app.region=eu-west-1
""");
System.setProperty("app.greeting", "from a system property");
System.setProperty("spring.application.json",
"{\"app\":{\"greeting\":\"from spring.application.json\"}}");
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
PropertyPrecedence.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
PropertyPrecedence.class);
app.setDefaultProperties(Map.of(
"app.greeting", "from default properties",
"app.timeout", "30s"));
String[] commandLine = {"--app.greeting=from the command line"};
try (ConfigurableApplicationContext context = app.run(commandLine)) {
ConfigurableEnvironment env = context.getEnvironment();
System.out.println("app.greeting = " + env.getProperty("app.greeting"));
System.out.println("app.region = " + env.getProperty("app.region"));
System.out.println("app.timeout = " + env.getProperty("app.timeout"));
System.out.println();
System.out.println("Property sources, highest precedence first:");
for (PropertySource<?> source : env.getPropertySources()) {
Object value = source.getProperty("app.greeting");
System.out.println(" " + source.getName()
+ (value == null ? "" : "\n app.greeting=" + value));
}
}
}
}
app.greeting = from the command line
app.region = eu-west-1
app.timeout = 30s
Property sources, highest precedence first:
configurationProperties
app.greeting=from the command line
commandLineArgs
app.greeting=from the command line
spring.application.json
app.greeting=from spring.application.json
systemProperties
app.greeting=from a system property
systemEnvironment
random
Config resource 'class path resource [application.properties]' via location 'optional:classpath:/'
app.greeting=from application.properties
applicationInfo
defaultProperties
app.greeting=from default properties
came from the command line, the highest source in the list. Every lower source still holds its own value; nothing is overwritten, the lookup simply stops at the first match.app.greeting exists only inapp.region andapplication.properties only in the default properties, so each was found further down the list.app.timeout- The first source,
, is not a real source. Spring Boot attaches it as a view over all the others, which is how relaxed names such asconfigurationProperties can matchAPP_GREETING .app.greeting came from the system property of that name and sits above ordinary system properties. Thespring.application.json environment variable is read the same way.SPRING_APPLICATION_JSON servesrandom ,${random.uuid} and similar values, and${random.int} holdsapplicationInfo andspring.application.pid .spring.application.version- The config file appears as
, found through the default locationclass path resource [application.properties] . Theoptional:classpath:/ prefix is why an application with nooptional: still starts.application.properties
Within config data, a profile-specific file such as application-prod.propertiesapplication.properties/configconfig/
@Value: one value, with defaults and SpEL
A mail client needs a host, a port, a timeout, a size limit and a list of recipients, so one bean shows each kind of conversion. The file leaves out the port and the sender to show both kinds of default:
package props.value;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;
@SpringBootApplication
public class ValueInjection {
@Component
static class MailSettings {
@Value("${mail.host}")
String host;
@Value("${mail.port:25}")
int port;
@Value("${mail.timeout}")
Duration timeout;
@Value("${mail.max-attachment}")
DataSize maxAttachment;
@Value("${mail.recipients}")
List<String> recipients;
@Value("${mail.sender:no-reply@${mail.domain}}")
String sender;
@Value("#{${mail.port:25} == 465 ? 'SMTPS' : 'SMTP'}")
String protocol;
@Value("#{'${mail.host}'.toUpperCase()}")
String hostUpper;
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
mail.host=smtp.example.com
mail.domain=example.com
mail.timeout=10s
mail.max-attachment=5MB
mail.recipients=ops@example.com, dev@example.com
""");
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
ValueInjection.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
ValueInjection.class);
try (var context = app.run(args)) {
MailSettings mail = context.getBean(MailSettings.class);
System.out.println("host = " + mail.host);
System.out.println("port = " + mail.port + " (default after the colon)");
System.out.println("timeout = " + mail.timeout + " = "
+ mail.timeout.toMillis() + " ms");
System.out.println("maxAttachment = " + mail.maxAttachment + " = "
+ mail.maxAttachment.toBytes() + " bytes");
System.out.println("recipients = " + mail.recipients + " (size "
+ mail.recipients.size() + ")");
System.out.println("sender = " + mail.sender);
System.out.println("protocol = " + mail.protocol);
System.out.println("hostUpper = " + mail.hostUpper);
}
}
}
host = smtp.example.com
port = 25 (default after the colon)
timeout = PT10S = 10000 ms
maxAttachment = 5242880B = 5242880 bytes
recipients = [ops@example.com, dev@example.com] (size 2)
sender = no-reply@example.com
protocol = SMTP
hostUpper = SMTP.EXAMPLE.COM
had no value in the file, so the text after the colon,${mail.port:25} , was converted to an25 .int became10s , aPT10S of 10000 ms. A bare number would have meant milliseconds.Duration became 5242880 bytes. Spring's5MB uses binary units, so one megabyte is 1024 times 1024 bytes, not one million.DataSize- The comma-separated recipients became a
of 2 elements, with the space after the comma trimmed.List - A default can contain another placeholder:
resolved to${mail.sender:no-reply@${mail.domain}} .no-reply@example.com is a SpEL expression evaluated after the#{...} placeholders inside it were replaced, which produced${...} and the upper-case host.SMTP
@Value
@ConfigurationProperties: typed groups of settings
A shop's settings include a number, a duration, a size, a list, a map, a list of objects and a nested group. Binding them onto one record shows how each shape is written in a properties file:
package props.typed;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.util.unit.DataSize;
@SpringBootApplication
@ConfigurationPropertiesScan
public class TypedProperties {
@ConfigurationProperties("shop")
public record ShopProperties(
String name,
@DefaultValue("3") int maxRetries,
@DurationUnit(ChronoUnit.SECONDS) Duration cacheTtl,
DataSize maxUpload,
List<String> currencies,
Map<String, Integer> stockLimits,
List<Warehouse> warehouses,
@DefaultValue Payment payment) {
public record Warehouse(String code, String city) {
}
public record Payment(@DefaultValue("stripe") String provider,
@DefaultValue("5s") Duration timeout) {
}
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
shop.name=Corner Books
shop.cache-ttl=90
shop.max-upload=2MB
shop.currencies=GBP,EUR
shop.stock-limits.books=500
shop.stock-limits.maps=40
shop.warehouses[0].code=LON
shop.warehouses[0].city=London
shop.warehouses[1].code=MAN
shop.warehouses[1].city=Manchester
""");
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
TypedProperties.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
TypedProperties.class);
try (var context = app.run(args)) {
ShopProperties shop = context.getBean(ShopProperties.class);
System.out.println("name = " + shop.name());
System.out.println("maxRetries = " + shop.maxRetries() + " (from @DefaultValue)");
System.out.println("cacheTtl = " + shop.cacheTtl() + " (90 read as seconds)");
System.out.println("maxUpload = " + shop.maxUpload());
System.out.println("currencies = " + shop.currencies());
System.out.println("stockLimits = " + shop.stockLimits());
shop.warehouses().forEach(w -> System.out.println("warehouse = " + w));
System.out.println("payment = " + shop.payment());
System.out.println("bean name = "
+ context.getBeanNamesForType(ShopProperties.class)[0]);
}
}
}
name = Corner Books
maxRetries = 3 (from @DefaultValue)
cacheTtl = PT1M30S (90 read as seconds)
maxUpload = 2097152B
currencies = [GBP, EUR]
stockLimits = {books=500, maps=40}
warehouse = Warehouse[code=LON, city=London]
warehouse = Warehouse[code=MAN, city=Manchester]
payment = Payment[provider=stripe, timeout=PT5S]
bean name = shop-props.typed.TypedProperties$ShopProperties
- The file uses kebab-case (
,cache-ttl ) and the record uses camelCase. Relaxed binding matched them without any mapping.stock-limits was not in the file, somaxRetries supplied it. Without the annotation a missing@DefaultValue("3") would be 0.int became 1 minute 30 seconds, becauseshop.cache-ttl=90 changed the unit for bare numbers from milliseconds to seconds.@DurationUnit(ChronoUnit.SECONDS) created a map entry, andshop.stock-limits.books=500 the first element of a list of records.shop.warehouses[0].code- No
keys exist, yetshop.payment is notpayment : the emptynull on the parameter asks Spring Boot to create the nested record anyway, and its own defaults filled in@DefaultValue and 5 seconds.stripe - The bean is named
followed by the class name.shop- found the record and registered it, which constructor binding requires; a@ConfigurationPropertiesScan or@Component would not bind a record through its constructor.@Bean
| Feature | @ConfigurationProperties | @Value |
|---|---|---|
| Relaxed binding | Yes | Limited: write the key in kebab-case |
| Lists, maps and nested objects | Yes | Comma-separated lists only |
Bean Validation with @Validated | Yes | No |
| IDE completion through generated metadata | Yes, with spring-boot-configuration-processor | No |
| SpEL expressions | No | Yes |
Environment variables and relaxed binding
Containers and Kubernetes pass settings as environment variables, which cannot contain dots or dashes. The program starts a second JVM with four variables set, because a running JVM cannot change its own environment:
package props.env;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan
public class EnvVarBinding {
@ConfigurationProperties("app")
public record AppProperties(int maxRetries, String regionName, List<String> servers) {
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
launchChild();
return;
}
try (var context = SpringApplication.run(EnvVarBinding.class, args)) {
AppProperties app = context.getBean(AppProperties.class);
System.out.println(" maxRetries = " + app.maxRetries());
System.out.println(" regionName = " + app.regionName());
System.out.println(" servers = " + app.servers());
System.out.println(" @Value-style lookup of app.max-retries: "
+ context.getEnvironment().getProperty("app.max-retries"));
}
}
/** Starts this class again in a new JVM, with environment variables set. */
static void launchChild() throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
app.max-retries=3
app.region-name=eu-west-1
app.servers=a.example.com,b.example.com
""");
String java = ProcessHandle.current().info().command().orElseThrow();
ProcessBuilder child = new ProcessBuilder(java,
"-cp", dir + File.pathSeparator + System.getProperty("java.class.path"),
EnvVarBinding.class.getName(), "child");
child.environment().put("APP_MAXRETRIES", "7");
child.environment().put("APP_REGIONNAME", "us-east-2");
child.environment().put("APP_SERVERS_0", "c.example.com");
child.environment().put("APP_SERVERS_1", "d.example.com");
child.environment().remove("JAVA_TOOL_OPTIONS");
child.inheritIO();
System.out.println("application.properties says max-retries=3, region-name=eu-west-1,"
+ " servers=a,b");
System.out.println("Environment: APP_MAXRETRIES=7 APP_REGIONNAME=us-east-2"
+ " APP_SERVERS_0=c... APP_SERVERS_1=d...");
System.out.println("Bound values:");
System.out.flush();
int exit = child.start().waitFor();
System.out.println("child exit code " + exit);
}
}
application.properties says max-retries=3, region-name=eu-west-1, servers=a,b
Environment: APP_MAXRETRIES=7 APP_REGIONNAME=us-east-2 APP_SERVERS_0=c... APP_SERVERS_1=d...
Bound values:
maxRetries = 7
regionName = us-east-2
servers = [c.example.com, d.example.com]
@Value-style lookup of app.max-retries: 7
child exit code 0
overrodeAPP_MAXRETRIES=7 from the file. To get the variable name, replace dots with underscores, remove dashes and use upper case.app.max-retries=3 andAPP_SERVERS_0 replaced the whole list: the two servers from the file are gone, not merged. A number between underscores is a list index.APP_SERVERS_1 also returned 7. Lookups through thegetProperty("app.max-retries") , and thereforeEnvironment , match environment variables as long as the key is written in its canonical kebab-case form.@Value
The documented rule removes dashes, but Spring Boot also accepts the form with each dash turned into an underscore: run with APP_MAX_RETRIES=9APP_SERVERS_0
YAML files and spring.config.import
YAML suits nested settings and lists of objects. This program puts an application.yamlapplication.propertiesfeeds.owner
package props.yaml;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.DefaultResourceLoader;
@SpringBootApplication
@ConfigurationPropertiesScan
public class YamlAndImport {
@ConfigurationProperties("feeds")
public record FeedProperties(String owner, List<Feed> sources) {
public record Feed(String name, String url, int everyMinutes) {
}
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.yaml"), """
spring:
main:
banner-mode: off
config:
import:
- classpath:feeds-secrets.properties
- optional:file:./does-not-exist.properties
logging:
level:
root: WARN
feeds:
owner: yaml-owner
sources:
- name: news
url: https://example.com/news.xml
every-minutes: 15
- name: weather
url: https://example.com/weather.xml
every-minutes: 60
""");
Files.writeString(dir.resolve("application.properties"), """
feeds.owner=properties-owner
""");
Files.writeString(dir.resolve("feeds-secrets.properties"), """
feeds.api-token=t0k3n
""");
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
YamlAndImport.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
YamlAndImport.class);
try (var context = app.run(args)) {
FeedProperties feeds = context.getBean(FeedProperties.class);
System.out.println("owner = " + feeds.owner());
feeds.sources().forEach(f -> System.out.println("feed = " + f));
System.out.println("token = "
+ context.getEnvironment().getProperty("feeds.api-token"));
System.out.println("Config data sources:");
for (PropertySource<?> source : context.getEnvironment().getPropertySources()) {
if (source.getName().startsWith("Config resource")) {
System.out.println(" " + source.getName());
}
}
}
}
}
owner = properties-owner
feed = Feed[name=news, url=https://example.com/news.xml, everyMinutes=15]
feed = Feed[name=weather, url=https://example.com/weather.xml, everyMinutes=60]
token = t0k3n
Config data sources:
Config resource 'class path resource [application.properties]' via location 'optional:classpath:/'
Config resource 'class path resource [feeds-secrets.properties]' via location 'classpath:feeds-secrets.properties'
Config resource 'class path resource [application.yaml]' via location 'optional:classpath:/'
- The two feeds were read from the YAML list, with
bound toevery-minutes .everyMinutes isowner . When both formats sit in the same location, theproperties-owner file takes precedence, as the source order at the end shows..properties- The imported
supplied the token. An import is inserted directly below the document that declares it, here just abovefeeds-secrets.properties .application.yaml - The missing
was skipped silently. Withoutoptional:file:./does-not-exist.properties , startup fails withoptional: .ConfigDataLocationNotFoundException
Use one format per application to avoid that precedence question. spring.config.importEnvironmentconfigserver:configtree:[encoding=utf-8]
Validating settings at startup
A wrong setting should stop the application at startup, not cause a failure hours later. Adding @Validated
package props.validated;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.validation.annotation.Validated;
@SpringBootApplication
@ConfigurationPropertiesScan
public class ValidatedProperties {
@Validated
@ConfigurationProperties("payment")
public record PaymentProperties(
@NotBlank String apiKey,
@Min(1) @Max(10) int maxRetries,
@Valid Callback callback) {
public record Callback(@Pattern(regexp = "https://.*") String url) {
}
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
logging.pattern.console=%m%n
payment.api-key=sk_test_123
payment.max-retries=50
payment.callback.url=https://shop.example.com/paid
""");
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
ValidatedProperties.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
ValidatedProperties.class);
try {
app.run(args).close();
} catch (RuntimeException e) {
System.out.println("run() threw " + e.getClass().getSimpleName());
}
}
}
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'payment-props.validated.ValidatedProperties$PaymentProperties': Could not bind properties to 'ValidatedProperties.PaymentProperties' : prefix=payment, ignoreInvalidFields=false, ignoreUnknownFields=true
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target props.validated.ValidatedProperties$PaymentProperties failed:
Property: payment.maxRetries
Value: "50"
Origin: class path resource [application.properties] - 5:21
Reason: must be less than or equal to 10
Action:
Update your application's configuration
run() threw ConfigurationPropertiesBindException
- The application did not start.
threwrun() while the bean was being created.ConfigurationPropertiesBindException - Spring Boot's failure analyzer printed the report: the property
, its valuepayment.maxRetries , the reason, and the origin"50" , which is the line and column of the value.class path resource [application.properties] - 5:21 on@Valid extends validation to the nested record. Its URL starts withcallback , so it passed.https://
Validation needs a Bean Validation implementation on the classpath, which spring-boot-starter-validation@Validated
Traps that bind nothing
Configuration mistakes rarely fail loudly. This program runs three common ones, two of which start without any error:
package props.traps;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;
@SpringBootApplication
@ConfigurationPropertiesScan
public class PropertyTraps {
@ConfigurationProperties("orders")
public record OrderProperties(int maxItems, boolean expressShipping) {
}
@Component
static class Holder {
@Value("${orders.max-items}")
static int staticMaxItems;
@Value("${orders.max-items}")
int instanceMaxItems;
}
static class NotABean {
@Value("${orders.max-items}")
int maxItems;
}
static SpringApplication app(String properties) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), properties);
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
PropertyTraps.class.getClassLoader());
return new SpringApplication(new DefaultResourceLoader(resources), PropertyTraps.class);
}
public static void main(String[] args) throws Exception {
String base = """
spring.main.banner-mode=off
logging.level.root=OFF
orders.max-items=20
orders.express-shiping=true
""";
try (var context = app(base).run(args)) {
OrderProperties orders = context.getBean(OrderProperties.class);
System.out.println("1. Misspelt key orders.express-shiping=true:");
System.out.println(" expressShipping = " + orders.expressShipping());
System.out.println("2. @Value on a static field and on a new object:");
System.out.println(" static field = " + Holder.staticMaxItems);
System.out.println(" instance field = "
+ context.getBean(Holder.class).instanceMaxItems);
System.out.println(" new NotABean() = " + new NotABean().maxItems);
}
System.out.println("3. @Value for a property that is not defined:");
try {
SpringApplication strict = app(base);
strict.addPrimarySources(List.of(NeedsRegion.class));
strict.run(args).close();
} catch (RuntimeException e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
System.out.println(" startup failed: " + root.getMessage());
}
}
/** Not a @Component, so only the third run registers it. */
static class NeedsRegion {
@Value("${orders.region}")
String region;
}
}
1. Misspelt key orders.express-shiping=true:
expressShipping = false
2. @Value on a static field and on a new object:
static field = 0
instance field = 20
new NotABean() = 0
3. @Value for a property that is not defined:
startup failed: Could not resolve placeholder 'orders.region' in value "${orders.region}"
- The misspelt
matched no field, soorders.express-shiping=true stayedexpressShipping and nothing was reported.false ignores unknown keys by default. The configuration processor's metadata lets the IDE flag such typos, and@ConfigurationProperties turns them into startup errors.ignoreUnknownFields = false - The
field stayed 0. Spring injects into objects, not classes, and skips static fields. Inject into an instance field or a constructor instead.static also got 0, because Spring never saw the object.new NotABean() works only on beans that Spring creates.@Value- A
placeholder with no value and no default stopped startup with${orders.region} . This one at least fails early; give a default (Could not resolve placeholder ) when the value is optional.${orders.region:eu}
Two more are worth knowing. Keys in a file loaded by @PropertySourcelogging.*spring.main.*application.properties
Choosing how to configure
| Situation | Use |
|---|---|
| A group of related settings used by your code | A record with @ConfigurationProperties@ConfigurationPropertiesScan |
| One value in one class | @Value("${key:default}") |
| A value computed from other values | @Value |
| Settings that must be correct before the application runs | @Validated |
| Values that differ per environment | Profile-specific files or environment variables |
| Secrets | Environment variables, or spring.config.import |
| A one-off override when starting the jar | --key=value |
| Deeply nested settings or lists of objects | application.yaml |
For values that change between development, test and production, continue with logging.*