亲宝软件园·资讯

展开

Spring表达式语言SpEL用法详解

人气:3

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

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

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

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

(4)通过SpEL可以实现:

字面量的表示:

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());
 }
}

部分输出:

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论