Spring表現は変数置換を実現します.

2769 ワード

SpELプロファイルと機能特性
Spring表現言語(SpEL)は、クエリーをサポートし、実行中にオブジェクト図を操作する機能が強い表現言語です.SpEL言語の文法は統一ELに似ていますが、最も重要な機能は明示的な方法での呼び出しと基本文字列テンプレート関数です.
参考:https://www.cnblogs.com/best/p/5748105.html
 
Mavenプロジェクトでの追加依存
pom.xmlは以下の通りです.

    4.0.0

    com.SpEl
    Spring053
    0.0.1-SNAPSHOT
    jar

    Spring053
    http://maven.apache.org

    
        UTF-8
        4.3.0.RELEASE
    
    
        
            junit
            junit
            test
            4.10
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.aspectj
            aspectjweaver
            1.8.9
        
        
            cglib
            cglib
            3.2.4
        
    
 
変数と割り当て
変数:変数は、式の中で文法的な変数名を使用してExpressionPaser ep=new SpelExpressionParsser()//を参照することができます.コンテキスト変数Evaaluation Contect ctx=new StandardvationConttextを作成します.ctx.setVarable(“name”,“Hello”);System.out.println(p.parseExpression).getValue(ctx)
出力:ハロー割り当て:属性設定は、割り当て演算子を使用します.これは通常、setValueを呼び出して実行されますが、getValueを呼び出してもいいです.また、「榑榑varName=value」という形で変数に値を付けることもできます.System.out.prntln(p.parseExpression).getValue(ctx);
出力:Ryo
 
変数の置換を実現する例
二つの変数のalarmTime、locationに値を割り当てます.最後に他の文字列を含む表式で、実際に変数を出力する本当の値を使います.
public class SpelTest {

    public static void main(String[] args) {
        ExpressionParser ep = new SpelExpressionParser();
        //        
        EvaluationContext ctx = new StandardEvaluationContext();
        ctx.setVariable("alarmTime", "2018-09-26 13:00:00");
        ctx.setVariable("location", "  201  ");
        System.out.println(ep.parseExpression("       #{#alarmTime},    #{#location}", new TemplateParserContext()).getValue(ctx));
    }
}
メインメソッドを実行して、結果出力アラーム発生時間は2018-09-26 13:00で、位置は二階201のマシンルームです.