原文鏈接:http://www.yiidian.com/spring/spring-el-helloworld.html
在Spring3中就已經支持EL表達式了, Spring Expression Language(SpEL)是類似於OGNL和JSF EL的表達式語言, 能夠在運行時構建復雜表達式, 存取對象屬性、調用對象方法等, 而且所有的SpEL都支持XML和Annotation兩種方式, 使用的格式均為:#{SpEL expression}。
下面的例子,這個例子將展示如何利用SpEL注入String、Bean到屬性中。
一、編寫Bean類
Customer.java
package com.yiidian.domain;
import java.io.Serializable;
/**
*
* @author http://www.yiidian.com
*
*/
public class Customer implements Serializable{
private String name;
private String telephone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
}
CustomerDao接口:
/**
*
* @author http://www.yiidian.com
*
*/
public interface CustomerDao {
}
CustomerDaoImpl類:
注意:在這個類中注入Customer對象和custName的字符串。
package com.yiidian.dao.impl;
import com.yiidian.dao.CustomerDao;
import com.yiidian.domain.Customer;
/**
* @author http://www.yiidian.com
*
*/
public class CustomerDaoImpl implements CustomerDao {
private Customer customer;
private String custName;
public void setCustomer(Customer customer) {
this.customer = customer;
}
public void setCustName(String custName) {
this.custName = custName;
}
@Override
public String toString() {
return "CustomerDaoImpl [customer=" + customer + ", custName=" + custName + "]";
}
}
二、編寫applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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.xsd">
<bean id="customer" class="com.yiidian.domain.Customer">
<property name="name" value="張三"/>
<property name="telephone" value="13666666666"/>
</bean>
<bean id="customerDao" class="com.yiidian.dao.impl.CustomerDaoImpl">
<!--
#{customer}:注入Customer對象
#{customer.name}: 注入Cutomer的name屬性值
-->
<property name="customer" value="#{customer}"></property>
<property name="custName" value="#{customer.name}"></property>
</bean>
</beans>
三、編寫測試
package com.yiidian.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiidian.dao.CustomerDao;
/**
* @author http://www.yiidian.com
*
*/
public class Demo1 {
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerDao customerDao = (CustomerDao)context.getBean("customerDao");
System.out.println(customerDao);
}
}
四、運行結果
源碼下載:http://pan.baidu.com/s/1i4HlQzb
歡迎關注我的公眾號::一點教程。獲得獨家整理的學習資源和日常干貨推送。
如果您對我的系列教程感興趣,也可以關注我的網站:yiidian.com