Spring expression language basic example using xml based configuration.
Spring 3 introduced the Spring Expression Language (SpEL), a powerful expression language, used to wire values into bean’s properties.
It’s an expression language similar to other ELs, that supports querying and manipulating an object graph at runtime.
This page gives introduction to spring expression language with basic example using xml based configuration, you can see more examples
in the next pages. Here is the spring beans
package com.java2novice.beans;
public class Order {
private String item;
private String price;
private String address;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
package com.java2novice.beans;
public class PaymentGateway {
private String itemName;
private Order order;
public void setOrder(Order ord){
this.order = ord;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Order getOrder() {
return order;
}
public void processOrder(){
System.out.println("Processing order: "+order.getItem());
}
}
|
Here is the xml based configuration file, the spring expression language is enclosed with in "#{ expression language }",
watch below configuraton file closely. We are directly injecting values to the bean "beanOrder".
In the below xml, the expression language #{beanOrder} assigns "beanOrder" reference to order property, and
#{beanOrder.item} assigns beanOrder item name to item property.
<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-3.0.xsd">
<bean id="beanOrder" class="com.java2novice.beans.Order">
<property name="item" value="Java Book" />
<property name="price" value="Rs 22.50" />
<property name="address" value="India" />
</bean>
<bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway">
<property name="itemName" value="#{beanOrder.item}" />
<property name="order" value="#{beanOrder}" />
</bean>
</beans>
|
Spring demo class:
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.PaymentGateway;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
PaymentGateway gateway = (PaymentGateway) context.getBean("paymentGateway");
gateway.processOrder();
}
}
|
|