Sub topic 11
Injecting configuration with @Value and @ConfigurationProperties
This chapter assumes you can define beans with @Component and @Bean, and that you know constructor injection. It also assumes you use Spring Boot 3 (Spring Framework 6, Java 17 or later), which is why the examples use jakarta.* packages and records. Plain Spring supports @Value and @PropertySource, but @ConfigurationProperties binding is a Spring Boot feature.
Why configuration stays outside the code
Hostnames, ports, timeouts and feature switches change between your laptop, a test server and production. If they are hard-coded, each change needs a rebuild. Spring instead reads them from outside the compiled code and injects them into beans. The same artifact can then run in every environment.
Spring offers two main ways to receive these values:
@Valueinjects one value at a time into a field, a constructor parameter or a setter parameter.@ConfigurationPropertiesbinds a whole group of related properties to a typed object, which is itself a bean.
Both read from the Environment, the container's view of all property sources.
Where property values come from
The Environment merges several property sources into one ordered lookup. The first source that has the key wins. In Spring Boot, the order from highest to lowest priority is roughly:
- Command-line arguments such as
--mail.port=2525 - Java system properties such as
-Dmail.port=2525 - Operating system environment variables such as
MAIL_PORT - Profile-specific files such as
application-prod.properties application.propertiesorapplication.yml- Sources registered with
@PropertySource
A higher source overrides a lower one. This lets you keep safe defaults in application.properties and override a single value in production with an environment variable.
Injecting single values with @Value
Use ${...} to refer to a property key. A colon after the key supplies a default.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class PriceClient {
private final String baseUrl;
private final int timeoutMillis;
public PriceClient(
@Value("${prices.url}") String baseUrl,
@Value("${prices.timeout-ms:2000}") int timeoutMillis) {
this.baseUrl = baseUrl;
this.timeoutMillis = timeoutMillis;
}
public String describe() {
return baseUrl + " (timeout " + timeoutMillis + " ms)";
}
}With this class, prices.url is required. If no source defines it, the context fails at startup with an "Could not resolve placeholder" error. That failure is useful, because a missing setting shows up at deployment time and not at the first request. prices.timeout-ms is optional and falls back to 2000.
Spring converts the string to the parameter type. It handles int, boolean, Duration, enums and List<String> (from comma-separated text). A value that cannot be converted, such as abc for an int, also fails the startup.
SpEL expressions
@Value("#{...}") evaluates a Spring Expression Language (SpEL) expression instead of a placeholder. You can combine the two: @Value("#{'${app.admins}'.split(',')}"). SpEL is powerful, but it is evaluated from strings that the compiler does not check. Use it sparingly.
Limits of @Value
- Each use repeats the key as a string. Renaming a property means finding every occurrence.
- There is no grouping. A class that needs six settings needs six annotated parameters.
- There is no validation beyond type conversion.
- Matching is exact.
@Value("${mailHost}")will not findmail.host, so write keys in lowercase kebab-case (mail.host) and refer to them the same way. @Valuecannot inject into astaticfield, because Spring injects instances.
Binding groups with @ConfigurationProperties
For related settings, define a class or record whose components match the property names. Given this file:
mail.host=smtp.example.com
mail.port=2525
mail.timeout=10s
mail.retry.max-attempts=5This record binds all of them:
import java.time.Duration;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "mail")
public record MailProperties(
@NotBlank String host,
@Min(1) @Max(65535) int port,
@DefaultValue("5s") Duration timeout,
@DefaultValue Retry retry) {
public record Retry(@DefaultValue("3") int maxAttempts) {
}
}Points to notice:
- A record has one canonical constructor, so Spring Boot uses constructor binding automatically. The properties are immutable after startup.
mail.retry.max-attemptsbinds toretry.maxAttempts. Boot uses relaxed binding:max-attempts,maxAttempts,max_attemptsand the environment variableMAIL_RETRY_MAXATTEMPTSall reach the same component.@DefaultValuesupplies a value when the property is absent. On a nested record, a bare@DefaultValuecreates the nested object using its own defaults.@Validatedturns on Bean Validation for the bound object. You needspring-boot-starter-validationon the classpath. An invalid value, such as port0, stops the application at startup with a message that names the property.
Registering the properties bean
Annotating the record is not enough. It must be registered as a bean. Choose one of two ways:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}@ConfigurationPropertiesScan finds every @ConfigurationProperties class under the application's package. Alternatively, list classes explicitly with @EnableConfigurationProperties(MailProperties.class) on a @Configuration class, as the topic's earlier example does. Once registered, other beans inject it like any bean:
import org.springframework.stereotype.Service;
@Service
public class MailSenderService {
private final MailProperties props;
public MailSenderService(MailProperties props) {
this.props = props;
}
public String target() {
return props.host() + ":" + props.port();
}
}Choosing between the two
| Aspect | @Value | @ConfigurationProperties |
|---|---|---|
| Scope | One value | A prefix with many values |
| Key matching | Exact key | Relaxed (kebab-case, camelCase, underscores) |
| Validation | None built in | Bean Validation with `@Validated` |
| Nested structures | Not supported | Nested records, lists and maps |
| Defaults | In the placeholder (`:value`) | `@DefaultValue` or field initializers |
| SpEL | Supported | Not supported |
| Best for | One or two simple, isolated values | Any group of related settings |
A reasonable rule: use @ConfigurationProperties as soon as two or more settings belong together, and keep @Value for a lone value or for SpEL.
Common errors
- "Could not resolve placeholder 'x' in value "${x}"". The key is missing from every source. Add the property or give the placeholder a default.
- Properties bean not found. The record has
@ConfigurationPropertiesbut nobody registered it. Add@ConfigurationPropertiesScanor@EnableConfigurationProperties. - Validation annotations ignored.
@Validatedis missing, or the validation starter is not on the classpath. - A value stays
0ornull. A missing property with no default leaves a primitive at0and a reference atnull. Add a constraint such as@Min(1)or@NotBlankso the omission fails loudly. - Environment variable has no effect. The key may be written differently. Environment variables use uppercase and underscores instead of dots and dashes, and some other source with higher priority may override it.
Testing configuration without the container
Because MailProperties is a record with a constructor, a unit test can create one directly and skip Spring entirely:
import java.time.Duration;
class MailSenderServiceTest {
void targetCombinesHostAndPort() {
MailProperties props = new MailProperties(
"localhost", 25, Duration.ofSeconds(1), new MailProperties.Retry(1));
MailSenderService service = new MailSenderService(props);
// service.target() returns "localhost:25"
}
}This is the same benefit constructor injection gave you for other dependencies: the test passes plain objects. To test the binding itself, including relaxed names and validation, start a small context with Spring Boot's ApplicationContextRunner, or use @SpringBootTest(properties = {...}).
Exercise
A service needs report.output-dir (required), report.max-rows (default 1000) and report.timeout (default 30 seconds, must not be null). Write a record that binds these under the prefix report, and name two things that must be in place for the record to become a bean and for max-rows to be checked as positive.
Show answer
Use @ConfigurationProperties(prefix = "report") @Validated public record ReportProperties(@NotBlank String outputDir, @DefaultValue("1000") @Positive int maxRows, @DefaultValue("30s") Duration timeout) {}. The record must be registered, with @ConfigurationPropertiesScan on the application class or @EnableConfigurationProperties(ReportProperties.class) on a configuration class. The @Positive check also needs @Validated on the record and spring-boot-starter-validation on the classpath.
Exercise
The application starts locally but fails in production with "Could not resolve placeholder 'prices.url'". The production host sets the environment variable PRICES_URL. What are two likely causes, and how do you fix each?
Show answer
First, the variable may not be set for the process that runs the application, for example it is missing from the container or service definition. Set it there. Second, the placeholder may use a key that does not map to the variable name. In Boot, prices.url maps to PRICES_URL, but a key such as pricesUrl written in @Value will not. Use the lowercase kebab-case key prices.url and check which sources are active. As a safety net, add a default (${prices.url:http://localhost:8080}) only if a default is acceptable in production.