zoukankan      html  css  js  c++  java
  • spring in action 学习笔记十三:SpEL语言(Spring Expression Language)

      SpEl语言的目的之一是防止注入外部属性的代码硬代码化.如@Value("#{student.name}")这个注解的意思是把Student类的name的属性值注入进去。其中student指向Student,是Student的id.

    SpEl的作用是:

    1.The ability to reference beans by their IDs;

    2.Invoking methods and accessing propeerties on objects

    3.Mathmatical,relational,and logical operations on values

    4.Regular expression matching,

    5.Collection manipulation.

    SpEl的示例代码如下:

    一:注入基本类型以及Strinig 类型的情况:

    #{3.14}//注入double。

    #{1}//注入整形

    #{'I love our coutry'}//注入字符串

    #{false}//注入boolean.

    二:引用其他类的属性、方法。

    #{student.name}

    #{student.hello()}//其他类的方法

    #{student?.hello()}//这个表达式的意思是:如果student为null的情况下,不会调用hello()这个方法,在student不为空时会调用student这个方法。

    ?.称为type-safe operator.

    三:类中的静态变量和静态方法的调用。

    #{T(java.lang.Math).PI}//调用Math类中的静态变量。

    #{T(java.lang.Math).abs(-3)}//调用Math类中的静态方法。

    四:在集合中的运用。

    #{jukebox.song[2]}//把jukebox这个类中song中的第二个元素注入进来。
    其中Jukebox的代码如下:
     1 package com.advancedWiring.ambiguityIniAutowiring2;
     2 
     3 import org.springframework.beans.factory.annotation.Value;
     4 import org.springframework.stereotype.Component;
     5 
     6 import java.util.ArrayList;
     7 import java.util.List;
     8 
     9 /**
    10  * Created by ${秦林森} on 2017/6/10.
    11  */
    12 public class Jukebox {
    13     private List<String> song;
    14 
    15     public List<String> getSong() {
    16         return song;
    17     }
    18     public void setSong(List<String> song) {
    19         this.song = song;
    20     }
    21     public void IteratorList(){
    22         for(String s:song){
    23             System.out.println(s);
    24         }
    25     }
    26 }

    song注入值的.xml文件如下:

    1  <util:list id="list">
    2         <value>I</value>
    3         <value>am</value>
    4         <value>chinese</value>
    5     </util:list>
    6   <bean id="jukebox" class="com.advancedWiring.ambiguityIniAutowiring2.Jukebox" p:song-ref="list"/>

    所以#{jukebox.song[2]}也就是:#{'chinese'}

    选择运算符:     .?[]
    #{jukebox.songs.?[artist eq 'Aerosmith']}//这个表达式的意思是:选择jukebox的属性songs,和songs中的属性artist
    并且这个artist属性值为Aerosmith的值。

    .^[] for selecting the first matching entry and
    .$[] for selecting the last matching entry.


  • 相关阅读:
    POJ 2823 Sliding Window & Luogu P1886 滑动窗口
    Luogu P2970 [USACO09DEC]自私的放牧
    Luogu P2922 秘密消息
    Luogu P3353 在你窗外闪耀的星星
    Luogu P2580 于是他错误的点名开始了
    Floyd详解
    高精度模板
    51Nod P1100 斜率最大
    洛谷——P1025 数的划分
    洛谷——P1063 能量项链
  • 原文地址:https://www.cnblogs.com/1540340840qls/p/6984265.html
Copyright © 2011-2022 走看看