Injecting Values using Spring Expression Lanugage

Spring Expression Language (SpEL) enables you to evaluate an expression dynamically and then use it in Spring’s ApplicationContext. For example, you could use SpEL to wire one bean into another bean’s property by using the bean ID as the SpEL expression:

<propertyname="instrument" value="#{guitar}"/>

The same thing can be done without SpEL, then why it is needed?

Let’s say that you want to configure a new Instrument bean whose ID is puneet. Instead of performing his own song, Puneet is going to be wired to perform whatever song Kunnal plays. When you configure the puneet bean, you can use SpEL to copy Kunnal’s song into the song property like this:

<bean id="puneet" class="com.kruders.bean.Instrument">

You can also invoke a method using SpEL. Suppose you have a bean having currentSong() that returns a song to be sung. So it can be done like this:

<bean id="puneet" class="com.kruders.bean.Instrument">

SpEL expressions can be used with XML or annotation based configuration metadata for defining BeanDefinitions. In both cases the syntax to define the expression is of the form #{ <expression string> }.

Injecting values using XML

We can define the bean in the XML configuration and use SpEL to inject the bean’s properties into the dependent bean as shown below:

    <bean id="kunnal" class="com.kruders.bean.Instrument">
        <property name="instrument" value="Guitar" />
        <property name="song" value="Bailamos" />
    <bean id="puneet" class="com.kruders.bean.Instrument">
        <property name="instrument" value="Keyboard" />
        <property name="song" value="#{}" />

Click Here for source code.

Injecting values using Annotation

When using annotation-style value injection, we just need to substitute the value annotations with the SpEL expressions as shown below:

    public class Puneet {
	private String instrument;
	private String song;


Click Here for source code.

, , ,

No comments yet.

Leave a Reply