您的位置:首页 > 编程语言 > Java开发

(六)Spring表达式语言SpEl

2017-10-19 16:11 375 查看
第一步:xml文件中配置bean

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd"> <bean id="address" class="com.atguigu.spring.beans.spel.Address">
<!-- 使用spel为属性赋一个字面值 -->
<property name="city" value="#{'BeiJing'}"></property>
<property name="street" value="WuDaoKou"></property
4000
>
</bean>
<bean id="car" class="com.atguigu.spring.beans.spel.Car">
<property name="brand" value="Audi"></property>
<property name="price" value="800000"></property>
<property name="tyrePerimeter" value="#{T(java.lang.Math).PI*80}"></property>
</bean>
<bean id="person" class="com.atguigu.spring.beans.spel.Person">
<!--使用spel来应用其他的Bean  -->
<property name="car" value="#{car}"></property>
<!--使用spel来应用其他的Bean 的属性 -->
<property name="city" value="#{address.city}"></property>
<!--使用spel中使用运算符-->
<property name="info" value="#{car.price>300000?'金领':'白领'}"></property>
<property name="name" value="fangxinde"></property>
</bean>
</beans>


第二步:运行main方法

package com.atguigu.spring.beans.spel;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-spel.xml");
Address address=(Address) ctx.getBean("address");
System.out.println(address);
Car car=(Car) ctx.getBean("car");
System.out.println(car);
Person person=(Person) ctx.getBean("person");
System.out.println(person);
}
}


第三步:运行结果

Car’s Constructor…..

Address [city=BeiJing, street=WuDaoKou]

Car [brand=Audi, price=800000.0, tyrePerimeter=251.32741228718345]

Person [name=fangxinde, car=Car [brand=Audi, price=800000.0, tyrePerimeter=251.32741228718345], city=BeiJing, info=金领]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: