原文鏈接:http://www.yiidian.com/spring/spring-el-method.html
SpEL允許開發者用El運行方法函數,並且允許將方法返回值注入到屬性中。
一、編寫Bean類
TestMethod類
package com.yiidian;
/**
*
* @author http://www.yiidian.com
*
*/
public class TestMethod {
public Double getPrice(){
return 199.99D;
}
}
Customer類:
package com.yiidian.domain;
import java.io.Serializable;
/**
*
* @author http://www.yiidian.com
*
*/
public class Customer implements Serializable{
private String name;
private Double amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
@Override
public String toString() {
return "Customer [name=" + name + ", amount=" + amount + "]";
}
}
二、配置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="testMethod" class="com.yiidian.TestMethod"></bean>
<bean id="customer" class="com.yiidian.domain.Customer">
<property name="name" value="#{'yiidian'.toUpperCase()}"/>
<property name="amount" value="#{testMethod.getPrice()}"/>
</bean>
</beans>
注意:
#{'yiidian'.toUpperCase()}
: 這句代表調用字符串toUpperCase()方法#{testMethod.getPrice()}
: 這句代表調用TestMehod對象的getPrice()方法
三、編寫測試類
package com.yiidian.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiidian.domain.Customer;
/**
* @author http://www.yiidian.com
*
*/
public class Demo1 {
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Customer customer = (Customer)context.getBean("customer");
System.out.println(customer);
}
}
四、運行結果
源碼下載:http://pan.baidu.com/s/1bp31pSV
歡迎關注我的公眾號::一點教程。獲得獨家整理的學習資源和日常干貨推送。
如果您對我的系列教程感興趣,也可以關注我的網站:yiidian.com