Spring 系列篇之表達(dá)式語言(SpEL)

Spring 表達(dá)式語言(SpEL)支持在運行時查詢和操作對象。本篇文章我們來學(xué)習(xí),如何使用SpEL,并簡單介紹下,他在IoC容器中,扮演什么角色。

SpEL 使用

首先我來看一張類圖,圖中紅框標(biāo)注的是SpEL中重要的角色(接口)。

SpEL

接著我們來看看Spring 源碼org.springframework.expression.spel.spelExpressionMapWithVariables中一個測試?yán)?p>

@Test
@SuppressWarnings("serial")
public void spelExpressionMapWithVariables() {
    // (1) 創(chuàng)建一個解析器對象
    ExpressionParser parser = new SpelExpressionParser();
    // (2) 解析一個表達(dá)式對象
    Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1");
    // (3) 提供一個表達(dá)式運行環(huán)境
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariables(new HashMap<String, Object>() {
        {
            put("aMap", new HashMap<String, Integer>() {
                {
                    put("one", 1);
                    put("two", 2);
                    put("three", 3);
                }
            });

        }
    });
    // (4) 執(zhí)行表達(dá)式
    boolean result = spelExpression.getValue(ctx, Boolean.class);
    assertTrue(result);

}

可以看到當(dāng)我們需要使用SpEL時,需要有這幾步操作

  • (1) 創(chuàng)建一個解析器對象
  • (2) 解析一個表達(dá)式對象
  • (3) 提供一個表達(dá)式運行環(huán)境
  • (4) 執(zhí)行表達(dá)式
    這里我們重點講一下(2),我們在來看一張圖,這是官網(wǎng)列舉的SpEL所支持的表達(dá)式。
    expressions-language-ref

    我們挑選幾個來講解一下,(其它的老鐵們可以戳我看詳細(xì))

下面例子使用的通用代碼

創(chuàng)建parse對象

SpelExpressionParser parser = new SpelExpressionParser();
class A{
    public static int plus(Integer one,Integer two){
        return one + two;
    }
}

定義表達(dá)式執(zhí)行上下文

EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Method plus = A.class.getDeclaredMethod("plus",Integer.class,Integer.class);

Inline List(4.3.3)

解析字符串為List

List list = (List) parser.parseExpression("{1,2,3,4,'g'}").getValue();
List<Map> listMap = (List) parser.parseExpression("{{age:1},{age:2},{age:3}}").getValue();

Inline Maps(4.3.4)

解析字符串為Map

Map map = (Map) parser.parseExpression("{name:'lykos',age:18}").getValue();

Functions(4.3.10)

解析執(zhí)行方法,這里需要注意#plus,當(dāng)我們需要引用變量時需要加#

context.setVariable("plus",plus);
int plusResult = (Integer) parser.parseExpression("#plus(3,4)").getValue(context);

Expression templating(4.3.18)

模板表達(dá)式,這里需要注意的是,我們需要定義模板格式,也就是需要告知解析器哪些是需要解析成表達(dá)式的,這個格式定義需要實現(xiàn)ParseContext接口,ParserContext.TEMPLATE_EXPRESSION是Spring提供的默認(rèn)格式(表達(dá)式需要用#{expression}

String plusResult = (String) parser.parseExpression("3 plus 4 is #{#plus(3,4)}", ParserContext.TEMPLATE_EXPRESSION).getValue(context);
String plusResult2 = (String) parser.parseExpression("custom parsercontext 3 plus 4 is $[#plus(3,4)]", new ParserContext() {
    @Override
    public boolean isTemplate() {
        return true;
    }
    //前綴字符
    @Override
    public String getExpressionPrefix() {
        return "$[";
    }
    //后綴字符
    @Override
    public String getExpressionSuffix() {
        return "]";
    }
}).getValue(context);

SpEL 在IoC容器中使用

Spring 容器中也是支持SpEL的。因為在AbstractApplicationContext.prepareBeanFactory方法中會添加BeanExpressionResolver(Bean定義的表達(dá)式解析接口)對象值,BeanExpressionResolver本身是一個接口,定義如下,其主要作用就是根據(jù)一個表達(dá)式解析出對象。他的實現(xiàn)類是StandardBeanExpressionResolver

public interface BeanExpressionResolver {
    Object evaluate(@Nullable String value, BeanExpressionContext evalContext) throws BeansException;
}

StandardBeanExpressionResolver內(nèi)部是包裝了ExpressionParser對象,我們在看看evaluate的實現(xiàn),可以確定的是StandardBeanExpressionResolver對象解析也是使用了SpEL。

public Object evaluate(@Nullable String value, BeanExpressionContext evalContext) throws BeansException {
    if (!StringUtils.hasLength(value)) {
        return value;
    }
    try {
        Expression expr = this.expressionCache.get(value);
        if (expr == null) {
            expr = this.expressionParser.parseExpression(value, this.beanExpressionParserContext);
            this.expressionCache.put(value, expr);
        }
        StandardEvaluationContext sec = this.evaluationCache.get(evalContext);
        if (sec == null) {
            sec = new StandardEvaluationContext(evalContext);
            sec.addPropertyAccessor(new BeanExpressionContextAccessor());
            sec.addPropertyAccessor(new BeanFactoryAccessor());
            sec.addPropertyAccessor(new MapAccessor());
            sec.addPropertyAccessor(new EnvironmentAccessor());
            sec.setBeanResolver(new BeanFactoryResolver(evalContext.getBeanFactory()));
            sec.setTypeLocator(new StandardTypeLocator(evalContext.getBeanFactory().getBeanClassLoader()));
            ConversionService conversionService = evalContext.getBeanFactory().getConversionService();
            if (conversionService != null) {
                sec.setTypeConverter(new StandardTypeConverter(conversionService));
            }
            customizeEvaluationContext(sec);
            this.evaluationCache.put(evalContext, sec);
        }
        return expr.getValue(sec);
    }
    catch (Throwable ex) {
        throw new BeanExpressionException("Expression parsing failed", ex);
    }
}

還記得@Value這個注解么,我們經(jīng)常用他來對我們的屬性賦值,如下

@Value("name")
private String name;

@Value("#{b.age}")
private String name;

@Value("${name}")
private String name;

@Value("name")

是直接給變量賦name

@Value("#{b.age}")

是獲取容器中b對象age屬性值

@Value("${name}")

是獲取配置文件中name值

感謝

感謝各位老鐵花時間觀看!
歡迎留言指正!
內(nèi)容持續(xù)更新!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容