SpringEL-HelloWorld

在Spring3中就已经支持EL表达式了, Spring Expression Language(SpEL)是类似于OGNLJSF 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

热门文章

优秀文章