Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
Spring Expression Language (SpEL) is a powerful expression language that enables querying and manipulating objects at runtime. Introduced in Spring 3.0, SpEL can be used in XML and annotations to communicate (read and write) with properties, invoke methods, navigate objects, and more, all during the runtime of a Spring application.
NullPointerException
using the safe navigation operator (?.
).T()
for type conversion.name
, account.name
names[0]
userMap['admin']
getAccounts()
, calculateAge()
1 + 1
, account.balance > 1000
T(java.lang.String)
, T(java.util.Date)
#variableName
<bean id="sampleBean" class="com.example.SampleBean"> <property name="value" value="#{anotherBean.propertyName}" /> </bean>
@Value("#{systemProperties['user.region']}") private String defaultLocale;
@Value("#{user?.address?.zipcode}") private String zipcode;
@Value("#{T(java.lang.Math).PI}") private double piValue;
@Value("#{list.![someProperty]}") private List<String> projectedProperties; @Value("#{map.?[value > 10]}") private Map<String, Integer> filteredMap;
SpEL expressions can be evaluated using the ExpressionParser
. The StandardEvaluationContext
can be used to set variables, root objects, and other properties that the expression might need during evaluation.
ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("'Hello World!'.concat('!')"); String result = (String) exp.getValue();
SpEL offers extensive functionalities that cover a wide range of use cases. Whether you're configuring beans in XML, using annotations, or even working programmatically with Spring's API, SpEL provides a flexible way to define dynamic values and compute them at runtime.
Introduction to SpEL in Spring framework:
// SpEL example in XML configuration <bean id="person" class="com.example.Person"> <property name="fullName" value="#{ 'John ' + 'Doe' }" /> </bean>
Using SpEL for expression evaluation in Spring:
// SpEL example in annotation @Value("#{ T(java.lang.Math).random() * 100.0 }") private double randomValue;
Dynamic property access with SpEL in Spring:
// SpEL dynamic property access @Value("#{ systemProperties['java.home'] }") private String javaHome;
Conditional expressions with SpEL in Spring:
// SpEL conditional expression @Value("#{ user.age >= 18 ? 'Adult' : 'Minor' }") private String userStatus;
How to use SpEL in Spring annotations:
// SpEL in annotation @Value("#{ environment['app.mode'] }") private String appMode;
Integration of SpEL with Spring XML configuration:
// SpEL in XML configuration <property name="discount" value="#{ order.totalAmount > 1000 ? 0.1 : 0.05 }" />
Accessing beans and properties with SpEL in Spring:
// SpEL accessing beans and properties @Value("#{ userService.getUser().fullName }") private String userFullName;