前段时间偶然看到Spel表达式,有点熟悉又有点陌生,我使用的有点少,稍微记录一下,以备不时之需。
介绍
中文spring官网:https://itmyhome.com/spring/expressions.html
英文spring官网:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions
Spel表达式是什么?
Spring表达式语言(简称SpEl,Spring Expression Language)是一个支持查询和操作运行时对象导航图功能的强大的表达式语言. 它的语法类似于传统EL,但提供额外的功能,最出色的就是函数调用和简单字符串的模板函数。简单来说就是可以帮助我们简化开发,减少一些逻辑、配置的编写。
表达式语言给静态Java语言增加了动态功能。
SpEL是单独模块,只依赖于core模块,不依赖于其他模块,可以单独使用。
什么时候可以用到SpEL表达式?
@Value注解可以通过@Value(“${xxxx}”)的形式来获取application当中的配置,使用@Value(“#{xxxx}”)的形式可以使用SpEL表达式
关于的Spel表达式在@Value注解中的具体用法,可以参考https://blog.csdn.net/weixin_45614626/article/details/120850552
spring cache当中@Cache相关的注解当中的key属性值可以使用SpEL表达式
@Override
@Cacheable(value = "rbac:roleSet", key = "T(org.apache.commons.lang3.StringUtils).join(#roles,'|')", unless = "#result == null || #result.size() == 0")
public List<String> getRoleIdsByRole(Set<String> roles) {
return null;
}
xml当中bean标签下property属性注入,是利用属性set方法注入的,然后使用spel表达式也是#{ }
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>
<!-- other properties -->
</bean>
<!--numberGuess.randomNumber相当于是从容器当中获取numberGuess的randomNumber 属性 -->
<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
<property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>
<!-- other properties -->
</bean>
SPEL表达式还可以进行权限控制(https://blog.csdn.net/qq_42764468/article/details/127782438)
具体用法还可以参考下面文章