Sub topic 4
Reading single values with @Value and Environment
This chapter assumes you can write a Spring Boot application with constructor injection and that you have an application.yaml file. You should also know how Boot orders property sources, which an earlier chapter covered. Here you will read individual configuration values with @Value and with the Environment abstraction. You will also see where each one fails.
Two ways to read one value
Both tools read from the same place. Boot merges every property source (files, environment variables, command-line arguments) into one Environment. Whatever wins the precedence contest is what both tools see.
@Valueinjects a value into a field, a constructor parameter or a method parameter when the bean is created.Environmentis a bean you inject and query at runtime, by key.
A complete example
Start with the configuration file.
app:
region: eu-west-1
mail:
host: localhost
port: 1025
retry-attempts: 3
features:
allowed-origins: http://localhost:3000,http://localhost:8080The class below reads the same file both ways. It runs once at startup and prints what it found.
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Component
class SettingsReport implements CommandLineRunner {
private final String host;
private final int port;
private final List<String> origins;
private final String timeZone;
private final Environment env;
SettingsReport(@Value("${app.mail.host}") String host,
@Value("${app.mail.port}") int port,
@Value("${app.features.allowed-origins}") List<String> origins,
@Value("${app.time-zone:UTC}") String timeZone,
Environment env) {
this.host = host;
this.port = port;
this.origins = origins;
this.timeZone = timeZone;
this.env = env;
}
@Override
public void run(String... args) {
System.out.println("host = " + host + ", port = " + port);
System.out.println("origins = " + origins);
System.out.println("timeZone = " + timeZone);
System.out.println("region = " + env.getRequiredProperty("app.region"));
System.out.println("retries = "
+ env.getProperty("app.mail.retry-attempts", Integer.class, 3));
}
}Run it with --app.mail.port=2525 and the output shows port = 2525. The command-line argument outranks the file. The timeZone line prints UTC because app.time-zone is not defined anywhere and the default after the colon applies.
How @Value placeholders work
Placeholders and defaults
${key} is a property placeholder. Spring replaces it with the value from the Environment before it converts the result to the parameter type. The text after the first colon is the default: ${app.time-zone:UTC}.
- No default and no key: startup fails with an
IllegalArgumentExceptionsayingCould not resolve placeholder 'app.mail.host'. This is useful for required settings. - Empty default:
${app.nickname:}yields an empty string, notnull. - Nested placeholders: a default can itself be a placeholder, as in
${app.backup-host:${app.mail.host}}. - Null default:
${app.nickname:#{null}}yieldsnull. This uses SpEL, covered below.
Type conversion
Spring converts the resolved string to the target type. int, boolean, Duration and enums work as you would expect. A comma-separated string becomes a List<String> or String[], which is why origins works above. A value that cannot convert, such as port: abc for an int, fails at startup with a conversion error.
SpEL expressions
#{...} is a Spring Expression Language (SpEL) expression. SpEL is evaluated after placeholders are resolved, so you can combine the two:
@Value("#{systemProperties['user.dir']}")
private String workingDirectory;
@Value("#{${app.mail.port} + 1}")
private int nextPort;SpEL is powerful, but it hides logic inside a string that the compiler cannot check. Use it sparingly.
How Environment works
Environment gives you lookups by key, with explicit control over missing values.
| Method | Missing key |
|---|---|
| `getProperty(key)` | returns `null` |
| `getProperty(key, default)` | returns the default |
| `getProperty(key, Type.class)` | returns `null` |
| `getProperty(key, Type.class, default)` | returns the default |
| `getRequiredProperty(key)` | throws `IllegalStateException` |
| `containsProperty(key)` | returns `false` |
Environment also exposes getActiveProfiles(), which returns the profiles that are active right now.
Use Environment when the key is not known until runtime, such as a key built from a tenant name. Also use it when "missing" is a normal case your code handles with a branch. For fixed keys, @Value is shorter.
Naming rules for @Value
Relaxed binding gets less help here than in @ConfigurationProperties. Always write the key in canonical form: lowercase, kebab-case, dots between levels.
// Recommended: canonical form
@Value("${app.mail.retry-attempts:3}") int retries;
// Risky: this only matches a property spelled exactly this way
@Value("${app.mail.retryAttempts:3}") int retriesCamel;With the canonical form, Boot's mapping lets environment variables work. APP_MAIL_RETRYATTEMPTS=5 overrides app.mail.retry-attempts. The mapping replaces dots with underscores, removes dashes and uppercases the name. With the camelCase placeholder, the same variable does not match, and the default of 3 is used silently.
Common errors
- Static or
finalfields. Spring does not inject into static fields. Put@Valueon an instance field, a constructor parameter or a setter. - Using the value too early. A field injected with
@Valueis stillnullinside a constructor if you used field injection. Prefer constructor parameters, as in the example. - Creating the object with
new. Spring only injects into beans it manages.new SettingsReport(...)skips injection entirely. - Confusing
$and#.${...}reads a property.#{...}evaluates an expression.@Value("#{app.mail.host}")does not read your property. - Expecting validation.
@Valuehas no@Validatedsupport and no metadata for IDE completion. A bad port such as70000passes unless you check it yourself. - Scattering keys. Ten classes each holding
${app.mail.host}means ten places to update when a key is renamed.
Choosing between the tools
| Need | Use |
|---|---|
| One or two fixed, simple values | `@Value` |
| A key computed at runtime, or optional-value branching | `Environment` |
| A group of related values, validation, IDE help | `@ConfigurationProperties` (next chapters) |
A rule of thumb: when you reach a third @Value with the same prefix, switch to a properties class.
Exercise
A class has the field @Value("${app.mail.retryAttempts:3}") int retries;. The file contains app.mail.retry-attempts: 5, and you start the app with APP_MAIL_RETRYATTEMPTS=7. What value does retries have, and how would you fix the placeholder?
Show answer
It is 3. The camelCase key app.mail.retryAttempts matches neither the YAML key nor the environment variable mapping, so the default applies silently. Rewrite the placeholder in canonical form, ${app.mail.retry-attempts:3}. Then the environment variable wins and retries is 7.
Exercise
You need a value that may or may not be set, and you want null when it is absent rather than an empty string. Show two ways to get it.
Show answer
With @Value, use a SpEL null default: @Value("${app.nickname:#{null}}") String nickname. With Environment, call env.getProperty("app.nickname"), which returns null for a missing key. ${app.nickname:} would give an empty string instead.