温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring表达式语言SpEL的用法

发布时间:2021-09-14 23:02:30 来源:亿速云 阅读:137 作者:chen 栏目:编程语言

这篇文章主要介绍“Spring表达式语言SpEL的用法”,在日常操作中,相信很多人在Spring表达式语言SpEL的用法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spring表达式语言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()); }}

到此,关于“Spring表达式语言SpEL的用法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI