Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 119 ยท Spring Framework

Spring Expression Language (SpEL) and @Value

Learn the difference between ${...} and #{...}, inject values with @Value, use SpEL operators, selection and safe navigation, and master every autowiring mode.

Spring has two small languages hidden inside annotation strings. The first is the property placeholder, ${app.page-size:20}, which looks up a configuration value. The second is the Spring Expression Language (SpEL), #{...}, a real expression language with operators, method calls and collection filters. You meet both in @Value, and SpEL turns up again in @Cacheable keys, @PreAuthorize rules, @EventListener conditions and many other places.

This lesson explains how the two differ and in which order Spring evaluates them, teaches the parts of SpEL you will actually use, and shows the pitfalls of @Value. It finishes with a close look at autowiring: how Spring fills a parameter of type Optional<T>, List<T>, Map<String, T> or ObjectProvider<T>. As in the other Spring lessons, the Spring code is read-only, and each mechanism comes with a small runnable model in plain Java. You should know Beans, Configuration and Component Scanning and Dependency Injection first.

${...} and #{...} are different things

They look alike, but they are processed by different parts of Spring:

Property placeholder ${...} SpEL expression #{...}
What it does looks up a key in the Environment evaluates an expression
Data source property files, environment variables, command-line arguments beans, system properties, literals, method results
Default value ${key:default} Elvis operator: #{x ?: 'default'}
Result type always a string, converted afterwards any object
Typical use configuration values computed values, conditions, cache keys, security rules
Java
@Component
public class CatalogSettings {
    CatalogSettings(
        @Value("${app.page-size:20}") int pageSize,                    // placeholder with a default
        @Value("#{T(java.lang.Runtime).getRuntime().availableProcessors()}") int cpus,  // SpEL
        @Value("#{'${app.name}'.toUpperCase()}") String banner,         // both: placeholder first
        @Value("Shop #{2 * 12} hours, region ${app.region}") String text) { ... }
}

The order matters: inside @Value, Spring resolves placeholders first, as plain text replacement, and only then evaluates SpEL on the result. So #{'${app.name}'.toUpperCase()} becomes #{'Bookshop'.toUpperCase()} and then BOOKSHOP. Forget the quotes and you get #{Bookshop.toUpperCase()}, where SpEL treats Bookshop as the name of a property or bean, and fails.

Placeholder resolution is a small algorithm worth seeing once: look in each property source in precedence order, substitute nested placeholders in keys, values and defaults, and detect cycles. The model below does all of that, including Spring Boot's mapping from app.region to an environment variable named APP_REGION.

Java A property placeholder resolver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The command-line value beats the file, and the environment variable APP_REGION beats app.region in the file, exactly as in Configuration, Properties and Profiles. Defaults can contain placeholders, and an empty default (${app.timeout:}) gives an empty string. The two #{...} lines show what SpEL receives after the placeholder pass: a quoted string literal in the first case, and a bare word that SpEL cannot resolve in the second.

The last two lines show the strict versus lenient difference. Spring Boot registers a strict resolver, so a missing key without a default stops the application at startup with "Could not resolve placeholder". A plain Spring application without a PropertySourcesPlaceholderConfigurer bean uses a lenient fallback that leaves ${app.missing} in the string, so the literal text ends up in your field. Strict is what you want: a typo should fail the deployment, not reach production.

The SpEL language

SpEL is evaluated against a root object (in @Value, the bean factory, which is how bean names and systemProperties become reachable) plus a set of variables written with #. Its most useful features:

Feature Example Result
Literals 'text', 42, 3.5, true, null quotes inside strings are doubled: 'it''s'
Arithmetic + - * / % ^ 7 / 2 is 3 (integer division), 2 ^ 10 is 1024
Relational == != < > <= >= or eq ne lt gt le ge the word forms avoid escaping in XML
Logical and or not (also `&&
Regex matches isbn matches '[0-9-]+'
Ternary cond ? a : b stock > 0 ? 'in stock' : 'sold out'
Elvis a ?: b a unless it is null (or an empty string), otherwise b
Safe navigation owner?.name null instead of an exception when owner is null
Properties, methods name.toUpperCase(), books[0].title, map['key'] getters are found by property name
Types T(java.time.Duration).ofSeconds(30) static methods and constants
Beans @clock.instant() or just clock in @Value another bean
Inline collections {1, 2, 3}, {currency: 'EUR', vat: 20} an immutable list or map
Selection books.?[price < 20] the elements that match
First / last match books.^[year > 2020], books.$[year > 2020] one element
Projection books.![title] a new list built from each element
Variables #user, #this, #root a variable, the current element, the root object

Selection and projection are the stars: they are a stream filter and map in a few characters. Inside the brackets, names refer to the current element, which you can also reach as #this.

To see how an expression language works, the next program implements a useful subset of SpEL: a tokenizer, a recursive-descent parser that builds a tree of lambdas, and an evaluator that finds properties and methods by reflection. It supports every feature in the table except types, beans, inline maps and the last-match operator.

Java A mini SpEL evaluator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program is long, but each part is small. tokenize splits the text into tokens and turns the word operators (gt, lt, ...) into symbols. Each parser method handles one precedence level, from the ternary at the top down to literals and names at the bottom, and returns a lambda (a Node), so the parsed expression can be evaluated many times, once per element in a selection. That's also what real SpEL does: parseExpression builds a tree once, and you can cache and reuse it.

Notice how the results match the table: 7 / 2 is 3 because both operands are integers, the selection .?[...] and projection .![...] chain like filter and map, owner?.name returns null quietly, while owner.name fails. The last two lines fail on purpose: navigating through null without ?., and a property that doesn't exist. Real SpEL reports these as SpelEvaluationExceptions with codes such as EL1007E ("cannot be found on null").

Evaluating SpEL in your own code

You rarely need it, but SpEL is a normal library you can call:

Java
ExpressionParser parser = new SpelExpressionParser();
Expression cheapTitles = parser.parseExpression("books.?[price < #limit].![title]");   // parse once

EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
context.setVariable("limit", 20);
List<?> titles = cheapTitles.getValue(context, shop, List.class);

StandardEvaluationContext enables everything: T(...) types, constructors, bean references and assignments. SimpleEvaluationContext allows only property access and a few safe features.

Never evaluate SpEL that comes from users with StandardEvaluationContext. An expression like T(java.lang.Runtime).getRuntime().exec('...') runs any command on your server. Spring Cloud Function and Spring Cloud Gateway both had critical remote-code-execution vulnerabilities of exactly this kind in 2022. Use SimpleEvaluationContext for anything influenced by input, or better, don't evaluate input as an expression at all.

SpEL in annotations

Many Spring annotations take SpEL, usually with method parameters available as variables (by name if the code is compiled with -parameters, which Spring Boot's build plugins configure, or as #p0, #a0):

Java
@Cacheable(cacheNames = "books", key = "#isbn", condition = "#isbn.length() == 13", unless = "#result == null")
public Book findByIsbn(String isbn) { ... }

@PreAuthorize("hasRole('ADMIN') or #username == authentication.name")
public Profile loadProfile(String username) { ... }

@PostFilter("filterObject.owner == authentication.name")       // filters the returned list
public List<Order> recentOrders() { ... }

@EventListener(condition = "#event.amount > 1000")
public void onLargePayment(PaymentReceived event) { ... }

@Scheduled(cron = "${jobs.cleanup.cron:0 0 3 * * *}")         // placeholders; "-" disables the job
public void cleanUp() { ... }

@ConditionalOnExpression("${feature.export:false} and '${spring.profiles.active:}' != 'test'")
@Configuration
class ExportConfig { ... }

Each annotation gets its own evaluation context with its own variables: #result in @Cacheable's unless, authentication, principal and hasRole(...) in method security (see Spring Security), #event in event listeners, and #root.methodName or #root.args in cache keys (Scheduling, Caching and Async). The mini evaluator's #user.roles.contains('ADMIN') or #user.name == 'dana' line is a @PreAuthorize rule in miniature. Note that @ConfigurationProperties does not evaluate SpEL; it only binds values.

@Value in practice

@Value receives a string and converts it to the target type with Spring's conversion service. Spring Boot's converters understand much more than numbers:

Field type Property value Notes
int, long, BigDecimal 25 whitespace is trimmed
boolean true, yes, on, 1 (and the opposites) anything else fails
Duration 30s, 500ms, 2h, PT30S without a unit, milliseconds
DataSize 10MB Spring Boot only
List<String>, String[] a, b, c split at commas
enum ACTIVE by name

Three pitfalls cause most @Value bugs. First, field injection happens after the constructor, so a constructor that reads an @Value field sees null or 0; use constructor parameters instead. Second, static fields are never injected; Spring only logs a message and moves on. Third, @Value works only on Spring-managed beans: an object you create with new keeps its defaults. The model below has all three, plus a missing key.

Java How Value fields are injected and converted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from top to bottom. The constructor ran before injection and saw null and 0. The container then filled every field, trimming " 25 ", parsing 30s and the ISO form PT0.5S as durations, accepting yes as true and splitting the host list. The static field stayed null. The object made with new got nothing at all. The last two lines fail on purpose: a missing key without a default, and a value that can't be converted to int (Spring wraps that in a TypeMismatchException).

The fix for the first two pitfalls is the same: put @Value on constructor parameters. Everything is then available in the constructor, the field can be final, and a unit test can pass values directly. For more than two or three related settings, prefer a typed @ConfigurationProperties record (Configuration, Properties and Profiles).

Autowiring modes in depth

@Value injects configuration; @Autowired (or a lone constructor) injects beans. Old XML configuration named its autowiring modes explicitly: no, byName, byType and constructor. Annotation-based Spring always works by type, with the name as a tie-breaker, and the parameter's declared type tells Spring what you want:

Parameter type Spring injects When nothing matches When several match
Notifier notifier the single bean of that type startup fails @Qualifier, then @Primary, then the bean whose name equals the parameter name, else startup fails
@Autowired(required = false) field or setter the bean, if any left untouched (null) same as above
Optional<Notifier> Optional.of(bean) Optional.empty() same as above
List<Notifier>, Notifier[] all beans, ordered by @Order / Ordered see note below all of them
Map<String, Notifier> all beans, keyed by bean name see note below all of them
ObjectProvider<Notifier> a lazy handle; you decide later getIfAvailable() returns null getIfUnique() returns null; stream() gives all

ObjectProvider is the most flexible: nothing is looked up until you call it, so it also solves the prototype-in-singleton problem from the previous lesson. If "zero beans" is a valid situation, provider.orderedStream() expresses "all of them, possibly none" most clearly. Spring also accepts the standard annotations: @Inject (from jakarta.inject) behaves like @Autowired, while @Resource (from jakarta.annotation) looks up by name first and falls back to the type. Generic types narrow candidates too: a Repository<Order> parameter ignores a bean of type Repository<Customer>.

The model below resolves each of those parameter shapes against a small set of beans.

Java Resolving Optional, List, Map and ObjectProvider

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three lines fail on purpose. A required MetricsClient doesn't exist, while Optional and getIfAvailable handle the same absence gracefully. A single Notifier named notifier is ambiguous, because two beans fit and neither name matches, and getObject() fails for the same reason. Renaming the parameter to smsNotifier resolves it by name. This works, but it is fragile: a rename refactoring silently changes which bean you get, so prefer an explicit @Qualifier or @Primary. Note also that the list follows @Order, not registration order, and that getIfUnique quietly returned the fallback where getObject failed.

Common pitfalls

  • ${...} where you meant #{...}, or the reverse. @Value("#{app.name}") looks for a bean called app; @Value("${2 * 3}") looks for a property named 2 * 3.
  • Unquoted placeholders inside SpEL. Write #{'${app.name}'.length()}, with quotes, when the value is text.
  • Reading @Value fields in a constructor, or expecting them on static fields or objects created with new.
  • Missing -parameters. Expressions like #isbn need parameter names in the bytecode; without them, use #p0.
  • Complex logic in annotations. A 200-character SpEL string has no compiler checks, no IDE refactoring and no unit tests. Move it into a bean method and call that: @PreAuthorize("@orderSecurity.canEdit(#orderId, authentication)").
  • Evaluating user input as SpEL. Covered above; it is a remote-code-execution hole.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. app.name=Bookshop. What does @Value("#{'${app.name}'.length()}") int n inject?

    Placeholders are resolved first, so SpEL evaluates 'Bookshop'.length(), which is 8. Without the quotes, SpEL would look for a bean or property named Bookshop and fail.
  2. 2. What does the SpEL expression books.?[price < 20].![title] return?

    .?[...] selects the matching elements and .![...] projects each of them, here to its title. .^[...] would return only the first match.
  3. 3. A bean has @Value("${app.max-items}") private int maxItems; and its constructor prints maxItems. What is printed?

    Spring must create the object before it can set its fields. Use a constructor parameter with @Value to have the value available in the constructor.
  4. 4. Two beans implement Notifier, neither is @Primary, and there are no qualifiers. Which injection point starts without an error?

    Collections and maps receive every candidate. A single Notifier (also inside Optional) is ambiguous, and getObject() fails for the same reason.
  5. 5. Why is evaluating a user-supplied string with StandardEvaluationContext dangerous?

    The standard context allows type references, constructors and bean access. Use SimpleEvaluationContext for anything influenced by input, or avoid evaluating input at all.

Summary

  • ${key:default} looks up configuration in the Environment; #{expression} evaluates SpEL. In @Value, placeholders are replaced first, then SpEL runs on the result.
  • Spring Boot resolves placeholders strictly: a missing key without a default fails at startup.
  • SpEL offers arithmetic, word operators (lt, gt, and), ternary, Elvis ?:, safe navigation ?., method calls, T(...) types, bean references, inline lists and maps, selection .?[...] and projection .![...].
  • SpEL powers @Cacheable keys and conditions, @PreAuthorize rules, @EventListener conditions and @ConditionalOnExpression. Keep those expressions short, and never evaluate user input with StandardEvaluationContext.
  • @Value converts strings to numbers, booleans (yes/on), durations (30s), lists and enums. Put it on constructor parameters; field injection happens after the constructor, and static fields are never injected.
  • Spring autowires by type, using @Qualifier, @Primary and the parameter name to break ties. Optional, List (ordered), Map (by bean name) and ObjectProvider (lazy, optional, unique or all) express exactly what you need.

Next: Aspect-Oriented Programming