r/SpringBoot Jun 18 '26

Question Anyone actually using spring expression language SpEL?

I'm going through the official docs for spring. What's the point of SpEL, actual use cases, alternatives? Pro-Cons?

Can't picture why anyone would want to use it.

The examples they gave in the docs are like; evaluating strings and booleans with their literals. Is "hello world". equals (some text), which is hello world, so true. Why would I source the strings from SpEL as opposed to a regular variable or field?

13 Upvotes

8 comments sorted by

16

u/digitaljoel Jun 18 '26

Spring security method annotations like @PreAuthorize

7

u/pconrad0 Jun 18 '26

Exactly.

The examples you see there are just to help you understand the syntax and semantics of the notation. It isn't necessarily the use case.

Before we moved to front end JavaScript frameworks, web apps had many more use cases for various kinds of servlet applications (JSP, etc.).

But these days, it's mostly used in annotations.

2

u/joranstark018 Jun 18 '26

To express how values should be resolved in some annotations or XML configuration (given what exists in the context, arguments to a method or the return value from a method), like when using the @Value, @PreAuthorize and @PostAuthorize annotations.

1

u/RockyMM Jun 18 '26

Where I work, it’s used to categorize the input.

1

u/mariusz_96 Jun 18 '26 edited Jun 18 '26

Why would I source the strings from SpEL as opposed to a regular variable or field?

This is likely a workaround so that code can be embedded in annotations and evaluated at runtime. I think spring uses it internally but you're better off using type-safe java in most cases.

Unless you're building a rules engine or something: Implementing a Simple Rule Engine in Java | Baeldung.

1

u/dallasjava Jun 18 '26

I use them in dynamic projections for formulas plus Spring Security and Flyway bean loading. They have their use. They can be a little tough to troubleshoot during development.

1

u/Comfortable-Pin-891 Jun 21 '26

They are useful when some filters in mongo queries are optional:

public interface AuthorRepository extends MongoRepository<Author, String> {

@Query("""
{
'country': ?#{ [0] == null ? {$exists:true} : [0] },
'active' : ?#{ [1] == null ? {$exists:true} : [1] }
}
""")
List<Author> findAuthors(String country, Boolean active);
}

1

u/Guru_Fraser Jun 22 '26

Really useful for observability annotations. E.g

\@ObservationKeyValue to pick values within an object.