加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

spring之spring表达式语言:SpEL

发布时间:2020-12-15 01:13:30 所属栏目:大数据 来源:网络整理
导读:(1)spring表达式语言是一个支持运行时查询和操作对象的表达式语言。 (2)语言类似于EL:SpEL使用#{...}作为定界符。所有在大括号中的字符串均被认为是SpEL。 (3)SpEL为bean的属性进行动态赋值提供了便利。 (4)通过SpEL可以实现: 通过Bean的id对Bean

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

     Car(String name) {
        this.name = name;
    }
    private String name;
    //轮胎周长
    private double tyrePerimeter;
    double price;
}

Address.java

 Address {
     String city;
     String street;
}

Student.java

 Student {
    
    int age;
     score;
     String info;
     Car car;
     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> ="address"="com.gong.spring.beans.spel.Address" p:city="武汉" p:street="#{'络南街道'}"="student"="com.gong.spring.beans.spel.Student"="tom" p:age="#{12}" p:score="#{99.00}"> <!-- 使用spel引用其它的bean --> property name value="#{car}"property> 使用spel引用其它bean的属性 ="city"="#{address.city}" 使用spel运算符 ,进行动态赋值="info"="#{car.price >300000 ? '有钱' : '没钱'}"</> beans>

Main.java

import org.springframework.context.ApplicationContext;
 org.springframework.context.support.ClassPathXmlApplicationContext;

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

部分输出:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读