Skip to content
Spring Boot Placeholder vs SpEL: How ${} and #{} Work Under the Hood

Spring Boot Placeholder vs SpEL: How ${} and #{} Work Under the Hood

This article explains the differences between Spring Boot's ${} placeholder resolution and #{} SpEL evaluation, detailing their syntax, source code implementations, parsing order in @Value, common pitfalls, and why @ConfigurationProperties doesn't support SpEL.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop

1. ${} and #{} Are Two Completely Different Things

1.1 Quick Distinction

Syntax: ${...} — Name: Property Placeholder — Essence: Retrieves property value from Environment, performs string replacement — Capability Boundary: Can only fetch existing properties, no expression evaluation

Syntax: #{...} — Name: SpEL Expression — Essence: Runtime-evaluated expression — Capability Boundary: Can access properties, methods, variables, beans; supports arithmetic and collection operations

1.2 Visual Comparison

// 1. Placeholder: replaces ${app.name} with string from config
@Value("${app.name}")
private String appName;

// 2. SpEL: evaluates expression, reads system property
@Value("#{systemProperties['user.dir']}")
private String workDir;

// 3. SpEL calls method, does arithmetic
@Value("#{T(java.lang.Math).random() * 100}")
private Double random;

1.3 Why They're Easily Confused

Both appear in @Value, config files, annotation parameters; look similar but:

Placeholder is "text replacement" — after replacement it's a plain value.

SpEL is an "expression program" — has its own syntax, types, and evaluation context.

Understanding this boundary clarifies parsing order and error troubleshooting.

2. How ${} Retrieves Values from Environment

2.1 Property Sources

Placeholder values come from Spring Environment 's PropertySource s, ordered by priority:

Command-line arguments
  ↓
OS environment variables
  ↓
Application config (application.yml/properties, including profiles)
  ↓
System properties (systemProperties)
  ↓
Default properties
Environment.getProperty("app.timeout")

searches in this order; first match wins.

2.2 Basic Syntax

${propertyName}
${propertyName:defaultValue}
propertyName

: key to look up.

Colon followed by defaultValue: used when property not found.

Default value can itself be another placeholder.

app:
  timeout: ${APP_TIMEOUT:3000}   # first check env var APP_TIMEOUT, else 3000

2.3 Nested Placeholders

Placeholders can nest; parsing resolves innermost first:

app:
  prefix: order
  topic: ${app.prefix}-notice
// Dynamic key: outer resolves inner placeholder first
@Value("${${app.prefix}.timeout:1000}")
private Integer timeout;

2.4 Core Parsing Components

PropertySourcesPlaceholderConfigurer : a BeanFactoryPostProcessor that replaces ${} placeholders in BeanDefinitions during bean definition loading phase.

PropertyPlaceholderHelper : utility that performs actual string replacement — identifies ${...}, recursively parses nesting, handles default values.

// Simplified logic
public String replacePlaceholders(String value, PropertyResolver resolver) {
    // 1. Find ${...}
    // 2. Split property name and default value (by first colon)
    // 3. resolver.getProperty(name) lookup
    // 4. If not found, use default; if neither, throw exception
    // 5. Recursively handle nested placeholders
}

2.5 Missing Placeholder Behavior

Property absent and no default → injection throws exception:

IllegalArgumentException: Could not resolve placeholder 'app.timeout'
in value "${app.timeout}"

Most common placeholder error; troubleshoot: check key spelling, PropertySource loading, profile activation.

2.6 Type Conversion

Placeholder replacement yields a string; injection into Integer, Boolean, Duration etc. uses Spring's type conversion system:

@Value("${app.timeout:3000}")
private Integer timeout;     // "3000" → 3000

@Value("${app.enabled:true}")
private Boolean enabled;     // "true" → true

3. SpEL Evaluation

3.1 Three Evaluation Essentials

Expression Parser — Role: Parses string into Expression — Typical Implementation: SpelExpressionParser Evaluation Context — Role: Provides root object, variables, bean resolver — Typical Implementation: StandardEvaluationContext Expression Object — Role: Reusable evaluation — Typical Implementation:

Expression

3.2 Basic Execution Flow

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name.length()");

StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(user);
context.setVariable("limit", 100);

Integer len = exp.getValue(context, Integer.class);

3.3 Common Syntax

Literals & Properties

"#{ 'hello' }"           // string literal
"#{user.name}"           // access root object property
"#{user['name']}"        // indexed access

Method Calls

"#{user.getName()}"
"#{T(java.lang.String).valueOf(100)}"   // T() references type

Variables & Beans

"#{#limit}"               // reference variable in context
"#{@orderService}"        // reference bean in container (@ prefix)

Safe Navigation & Elvis

"#{user?.address?.city}"  // ?. returns null if any part null, no NPE
"#{user.name ?: 'anonymous'}"  // ?: default if null/empty

Ternary & Collection Ops

"#{age > 18 ? 'adult' : 'minor'}"
"#{users.?[age > 18]}"    // selection: filter collection
"#{users.![name]}"        // projection: extract property

3.4 Root Object & Variables in Context

#root

: expression root object. #this: current evaluation object (changes during projection/selection).

In annotation scenarios, Spring puts method parameters, return value, bean resolver into context.

3.5 SpEL in Annotations

Beyond @Value, many Spring annotations use SpEL for dynamic rules:

// Cache key
@Cacheable(value = "user", key = "#userId")
public User getUser(Long userId) { ... }

// Security
@PreAuthorize("hasRole('ADMIN') and #user.dept == 'tech'")
public void delete(Long id) { ... }

// Conditional assembly
@ConditionalOnExpression("${app.feature.enabled:false}")

4. Source Code Chain

4.1 @Value Parsing Location

@Value

is processed by AutowiredAnnotationBeanPostProcessor during field injection. Handling a @Value string involves two steps:

1. First, placeholder resolution: replace ${...} with actual values from Environment
   ↓
2. Then, SpEL evaluation: if result contains #{...}, delegate to BeanExpressionResolver for evaluation

4.2 Parsing Order from Source Perspective

// Simplified flow
public Object resolveValue(String value, MethodParameter parameter) {
    // 1. Placeholder replacement (PropertySourcesPlaceholderConfigurer / Environment)
    String resolved = environment.resolvePlaceholders(value);

    // 2. SpEL evaluation (StandardBeanExpressionResolver)
    if (containsExpression(resolved)) {
        return beanExpressionResolver.evaluate(resolved, context);
    }
    return resolved;
}

4.3 Mixed Usage

Because placeholders are replaced first, then SpEL evaluated, you can combine them:

// First replace ${app.mode} with string, then SpEL evaluates condition
@Value("#{${app.mode: 'dev'} == 'prod' ? 'production' : 'development'}")
private String modeDesc;

4.4 Core Source Classes

PropertySourcesPlaceholderConfigurer

— Responsibility: Handles placeholders in BeanDefinition PropertyPlaceholderHelper — Responsibility: Placeholder recognition, nested parsing, default values Environment / PropertyResolver — Responsibility: Property lookup StandardBeanExpressionResolver — Responsibility: Bridges SpEL evaluation SpelExpressionParser — Responsibility: Parses expressions StandardEvaluationContext — Responsibility: Evaluation context Expression — Responsibility: Expression object, getValue evaluates

4.5 Why @ConfigurationProperties Doesn't Support SpEL

@ConfigurationProperties

uses Binder property binding : fetches values from Environment by field name, performs type conversion; the entire process bypasses the SpEL evaluator. Therefore, writing #{...} in a config class field won't be computed — this is a design boundary, not a bug.

5. Config References, Bean Injection & Annotation SpEL

5.1 Config File Internal References

app:
  name: order-service
  port: 8080
  url: http://${app.name}:${app.port}
  timeout: ${APP_TIMEOUT:3000}

5.2 Common @Value Combinations

@RestController
public class DemoController {

    // Pure placeholder
    @Value("${app.name}")
    private String appName;

    // Placeholder + default + type conversion
    @Value("${app.timeout:3000}")
    private Integer timeout;

    // SpEL references bean
    @Value("@orderService")
    private OrderService orderService;

    // SpEL reads system property
    @Value("#{systemProperties['java.version']}")
    private String javaVersion;

    // Safe navigation + Elvis
    @Value("#{@demoConfig.name ?: 'default-name'}")
    private String name;
}

5.3 SpEL on Method Parameters

@GetMapping("/{id}")
public Result get(@PathVariable Long id,
                  @Value("#{request.getHeader('X-Trace-Id')}") String traceId) {
    // ...
}

5.4 Cache & Security Expressions

@Cacheable(value = "user", key = "#userId", unless = "#result == null")
public User getUser(Long userId) { ... }

@PreAuthorize("#userId == authentication.principal.id")
public User detail(Long userId) { ... }

5.5 Reading Collection-Type Config

app:
  servers:
    - 10.0.0.1
    - 10.0.0.2
@Value("${app.servers}")
private List<String> servers;   // string split by comma then converted to List

Placeholder resolution, SpEL expressions, and the Environment property system are high-frequency topics in Spring Boot advanced and senior interviews. Understanding the boundaries and cooperation order of these two mechanisms enables you to reason about config binding, conditional assembly, annotation dynamic rules, and bean injection — and quickly troubleshoot issues like "config not fetched", "expression error", "default value not working".

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SpELSpring BootConfigurationProperties@ValueEnvironmentPropertySourcesPlaceholderConfigurerPlaceholder ResolutionStandardEvaluationContext
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.