spring之运行时装配bean属性

版权声明:文章编写不易,转载请注明原链接 https://blog.csdn.net/u012184539/article/details/84852856

一. 表达式界定符#{}

如果需要在运行时才装配bean的属性。Spring3引入了表达式语言Spring Expression language(SpEL)。SpEL使用#{}界定符把值装配到bean中。

<property name="message" value="I have #{5} apples"/>

可以使用浮点数

<property name="message" value="I have #{5.6} apples"/>

可以使用科学计数法

<property name="message" value="I have #{1e4} apples"/>

使用字面值
#{}里面使用字符串字面值时,用双引号或单引号

<property name="message" value="#{'I have '5} apples"/>

引用bean、properties和方法

<property name="message" value="#{user.getCount()} apples"/>

二. ?. null-safe运算符

在上面的表达式中,如果bean对象是null的时候,在调用对象的函数时会出现空指针异常。

<property name="message" value="#{user?.getCount()} apples"/>

在这里使用了?.运算符,当user为null时则不会调用getCount函数,避免了空指针异常。

三. T()运算符

使用T()运算符可以调用类的静态方法和静态成员。如下调用Math类的PI常量。

<property name="message" value="T(java.lang.Math).PI"/>

四. 常用运算符

在这里插入图片描述
SpEL支持Java的所有基础运算符,同时增加了^运算符执行乘方运算。
正则表达式运算符
如下判断用户名是否包含kity字符

<property name="message" value="#{user.name matches 'kity'}"/>

五. 高级运算符

  1. []
<property name="message" value="#{user.friends[1]'}"/>
  1. .?[]
    对集合成员进行过滤,如下筛选年龄大于18的用户
<property name="message" value="#{users.?[age gt 18]'}"/>
  1. .^[]
    查询集合的第一个匹配项
  2. .$[]
    查询集合的最后一个匹配项
  3. .![] 投影集合
    投影集合可以选择一个集合中的特定属性放到另一个集合中。如下把城市集合中的城市名字放到cityNames集合中。
<property name="cityNames" value="#{citys.![name]'}"/>

猜你喜欢

转载自blog.csdn.net/u012184539/article/details/84852856