当前位置: 移动技术网 > IT编程>开发语言>Java > Spring表达式语言SpEL用法详解

Spring表达式语言SpEL用法详解

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了spring表达式语言spel用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

(1)spring表达式语言是一个支持运行时查询和操作对象图得我强大表达式语言。

(2)语言类似于el:spel使用#{...}作为定界符。所有在大括号中的字符串均被认为是spel。

(3)spel为bean的属性进行动态赋值提供了便利。

(4)通过spel可以实现:

  • 通过bean的id对bean进行引用
  • 调用方法及引用对象的属性
  • 计算表达式的值
  • 正则表达式匹配

字面量的表示:

  • 整型:#{5}
  • 小数:#{3.45}
  • 科学计数法:#[1e4]
  • 字符串:可以使用单引号或双引号早味字符串的定界符:#{'tom'},#{"tom"}
  • 布尔值:#{false}

spel支持的运算符号:+ - * / % ^ < > == <= >= lt gt eq le ge and or not | (?:) if-else 正则表达式等等

调用静态属性和方法:通过t()

以下代码均忽略类中的getter、setter和to_string方法。

car.java

package com.gong.spring.beans.spel;
public class car {
 public car() {
 }
 public car(string name) {
  this.name = name;
 }
 private string name;
 //轮胎周长
 private double tyreperimeter;
 private double price;}

address.java

package com.gong.spring.beans.spel;

public class address {
 private string city;
 private string street;
}

student.java

package com.gong.spring.beans.spel;

public class student {
 
 private string name;
 private int age;
 private double score;
 private string city;
 private string info;
 private car car;
 private address address;
}

beans-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:p="http://www.springframework.org/schema/p"
 xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="car" class="com.gong.spring.beans.spel.car" p:name="baoma"   p:tyreperimeter="#{t(java.lang.math).pi*80}"></bean>
 <bean id="address" class="com.gong.spring.beans.spel.address" 
 p:city="武汉" p:street="#{'络南街道'}"></bean>

 <bean id="student" class="com.gong.spring.beans.spel.student" p:name="tom"
 p:age="#{12}" p:score="#{99.00}"> 
  <!-- 使用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>
 </bean>

</beans>

main.java

package com.gong.spring.beans.spel;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

public class main {
 public static void main(string[] args) {
  //1.创建spring的ioc容器对象
  applicationcontext ctx = new classpathxmlapplicationcontext("beans-spel.xml");
  //2.从容器中获取bean实例
  student student = (student) ctx.getbean("student");
  system.out.println(student.tostring());
 }
}

部分输出:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网