Spring 3 provides powerful Expression Language which can be used to wire beans. Lets take an example to demonstrate how SpEL is used to wire bean.
Product.java: The Product class contains property named part which is of Part type.
package spel.wiringbean;
import java.util.*;
import spel.wiringbean.Part;
public class Product
{
private Part part;
public void setPart(Part part) {
this.part = part;
}
public Part getPart() {
return part;
}
}
Part.java: This class contains the name of the part and will be used in configuration file to provide this name to the part property of Product bean.
package spel.wiringbean;
import java.util.*;
public class Part
{
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
spring-beans.xml: Using Spring expression language the property part of Product bean is wired with the part bean with the text #{part}.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="product" class="spel.wiringbean.Product">
<property name="part" value="#{part}"/>
</bean>
<bean id="part" class="spel.wiringbean.Part">
<property name="name" value="Monitor"/>
</bean>
</beans>
AppMain.java: This class loads the context configuration file spring-beans-list.xml from the class path.
package spel.wiringbean;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import spel.wiringbean.Product;
import spel.wiringbean.Part;
import java.util.*;
public class AppMain{
public static void main( String[] args ){
ApplicationContext appContext = new ClassPathXmlApplicationContext(new
String[] {"spel\\wiringbean\\spring-beans-list.xml"});
Product product = (Product)appContext.getBean("product");
System.out.println(product.getPart().getName());
}
}
The output of the above program will be as below:
Monitor
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.