Spring EL

在使用springboot的中使用过一次这SpEL,这种能够嵌入java的表达式语言不光SpEL这一种,还有很多种。这种语言很像脚本语言,动态的,但是能够嵌入java中,而且效率较低。

优点与其他动态语言一样,灵活,需求变化快的场景,可以使用这SpEL来写成配置文件的方式。在Stack Overflow上找到一个回答:

You can use SpEL as a simplified alternative to Java reflection. It reduces a lot of code for you. One of the use cases, I had at my work is to flatten a deep object graph to a name-value pair for indexing and lookup purposes.

The object graph can be extended by our customers in which case the additional properties should also be indexed. By using SpEL, the customers only need to write expressions in some properties file and the framework code takes care of extracting the new data.

All the use-cases of Java reflection are also potential use-cases for SpEL with added simplicity and reduced code.

上面的回答主要意思是再能够使用java反射的场景下很多能使用SpEL,使用了这SpEL能够简化很多代码。

几个用过的简单加载配置的例子:

    @Value("#{${config.random}}")
    Double random;

    @Value("#{${config.map}}")
    Map<String, String> map;

    // 类型是String和Integer都可以
    @Value("#{'${config.list}'.split(',')}")
    List<Integer> list;

对应的application.property内容:

config.random = T(java.lang.Math).random()
config.map={key1:'value1', key2:'value2'}
config.list=2,2,3,4

另外,SpEL还能读取bean实例,加载动态函数等,使用一些更复杂的场景。
代码路径:https://github.com/wangzhenyagit/springboot-learn/tree/master/SpEL

参考

SpEL官方文档
What are some valid uses for spEL (Spring Expression Language) ?
《Spring 5 官方文档》6.Spring表达式语言
Spring表达式语言 之 5.3 SpEL语法 ——跟我学spring3

Table of Contents