Spring-Bean配置-SpEL

Spring 表达式语言(简称SpEL):是一个支持运行时查询和操作对象图的强大的表达式语言。语法类似于 EL:SpEL 使用 #{…} 作为定界符,所有在大框号中的字符都将被认为是 SpEL
SpEL 为 bean 的属性进行动态赋值提供了便利

通过 SpEL 可以实现:通过 bean 的 id 对 bean 进行引用;调用方法以及引用对象中的属性;计算表达式的值;正则表达式的匹配

案例:三个bean,Person,Car,Adress,get set方法请自行产生

Adress类的属性:

   private String city;
   private String street;
Car类的属性:

    private String brand;
    private double price;
    //轮胎周长
    private double tyrePerimeter;
Person类的属性:

    private String name;
    private Car car;
    //引用address bean的city属性
    private String city;
    //根据car的价格确定info ,>300000金领  否则白领
    private String info;
applicationContext_spel.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<bean id="address" class="com.cgc.spring.beans.spel.Address">
	<!-- 使用spel为属性赋一个字面值 -->
		<property name="city" value="#{'BeiJing'}"></property>
		<property name="street" value="WuDaoKou"></property>
	</bean>
	
	<bean id="car" class="com.cgc.spring.beans.spel.Car">
		<property name="brand" value="Audi"></property>
		<property name="price" value="500000"></property>
		<!-- 使用spel引用类的静态属性 -->
		<property name="tyrePerimeter" value="#{T(java.lang.Math).PI*80}"></property>
	</bean>
	
	<bean id="person" class="com.cgc.spring.beans.spel.Person">
	    <!-- 在spel中使用其他的Bean -->
		<property name="car" value="#{car}"></property>
		<!-- 使用其他bean的属性 -->
		<property name="city" value="#{address.city}"></property>
		<!-- 在spel中使用运算符 -->
		<property name="info" value="#{car.price>300000? '金领' :'白领'}"></property>
	</bean>
		
</beans>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值