1. 程式人生 > 程式設計 >Spring表示式語言SpEL用法詳解

Spring表示式語言SpEL用法詳解

這篇文章主要介紹了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());
 }
}

部分輸出:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。