码迷,mamicode.com
首页 > 编程语言 > 详细

spring in action 学习笔记十三:SpEL语言(Spring Expression Language)

时间:2017-06-11 10:19:21      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:access   ring   abs   math   factory   for   not   mit   不为   

  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.


spring in action 学习笔记十三:SpEL语言(Spring Expression Language)

标签:access   ring   abs   math   factory   for   not   mit   不为   

原文地址:http://www.cnblogs.com/1540340840qls/p/6984265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!