SpEL integration with Spring annotations and XML¶
Spring Expression Language (SpEL) can be directly integrated into Spring configuration using XML metadata and Java annotations. This allows for dynamic bean wiring and value injection through expressions defined within #{ } delimiters^[600-developer-spring-spring-spel.md].
XML-based Configuration¶
In XML bean definitions, SpEL expressions are used within the value attribute of a property tag^[600-developer-spring-spring-spel.md]. For example, to wire a specific item from a list bean property, the expression can reference the bean ID and the list index^[600-developer-spring-spring-spel.md].
<bean id="training" class="com.geeksforgeeks.spring.Training">
<property name="topic" value="#{tutorial.topicsList[1]}"/>
</bean>
This configuration injects the second element of the topicsList from the tutorial bean into the topic property of the training bean^[600-developer-spring-spring-spel.md].
Annotation-based Configuration¶
SpEL is also supported within Spring annotations, such as @Value^[600-developer-spring-spring-spel.md]. By placing the expression string inside the annotation, dependencies can be injected directly into fields.
public class Training {
@Value("#{tutorial.topicsList[0]}")
private Topic defaultTopic;
// Getters and setters...
}
In this example, the defaultTopic field is populated with the first element retrieved from the tutorial bean's list^[600-developer-spring-spring-spel.md].
Expression Syntax¶
The core syntax for SpEL expressions in both XML and annotations is #{ <expression string> }^[600-developer-spring-spring-spel.md]. It is distinct from property placeholders, which typically use the ${ ... } syntax^[600-developer-spring-spring-spel.md].
Related Concepts¶
- [[SpelExpressionParser]]
- [[Spring @Value annotation]]
Sources¶
^[600-developer-spring-spring-spel.md]