SpringEL表达式(一)-入门案例
程序员文章站
2022-04-15 17:44:41
原文链接:http://www.yiidian.com/spring/spring el helloworld.html 在Spring3中就已经支持EL表达式了, Spring Expression Language(SpEL)是类似于OGNL和JSF EL的表达式语言, 能够在运行时构建复杂表达 ......
原文链接: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
欢迎关注我的公众号::一点教程。获得独家整理的学习资源和日常干货推送。
如果您对我的系列教程感兴趣,也可以关注我的网站:
推荐阅读