360SDN.COM

Spring Framework 5 权威指南(29)

来源:程序员阮威  2017-09-11 13:20:39    评论:0点击:

这是一个Spring 5专题系列,其诞生的动机是:

1.介绍最新版本的Spring Framework;

2.介绍最系统化的Spring Framework;

3.介绍最佳实践的Spring Framework;

7.运算符

关系运算符如下:

// evaluates to true

boolean trueValue = parser.parseExpression("2 == 2").getValue(Boolean.class);

 

// evaluates to false

boolean falseValue = parser.parseExpression("2 < -5.0").getValue(Boolean.class);

 

// evaluates to true

boolean trueValue = parser.parseExpression("'black' < 'block'").getValue(Boolean.class);

注意:1.null表示什么都没有(不是0),因此任何值都总是大于null值。

2.符号运算符可以替换为字母,例如:lt (<), gt (>), le (?),ge (>=), eq (==), ne (!=), div (/), mod (%), not (!)

SpEL还支持两个非标准的关系运算符:instanceofmatches(基于正则表达式)

// evaluates to false

boolean falseValue = parser.parseExpression(

                "'xyz'instanceof T(Integer)").getValue(Boolean.class);

 

// evaluates to true

boolean trueValue = parser.parseExpression(

                "'5.00'matches '\^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);

 

//evaluates to false

boolean falseValue = parser.parseExpression(

                "'5.0067'matches '\^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);

注意:1 instanceofT(int) 求值结果为false1 instanceof T(Integer) 求值结果为true

逻辑运算符如下:

// -- AND --

 

// evaluates to false

boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class);

 

// evaluates to true

String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')";

boolean trueValue =parser.parseExpression(expression).getValue(societyContext, Boolean.class);

 

// -- OR --

 

// evaluates to true

boolean trueValue = parser.parseExpression("true or false").getValue(Boolean.class);

 

// evaluates to true

String expression = "isMember('Nikola Tesla') or isMember('Albert Einstein')";

boolean trueValue =parser.parseExpression(expression).getValue(societyContext, Boolean.class);

 

// -- NOT --

 

// evaluates to false

boolean falseValue = parser.parseExpression("!true").getValue(Boolean.class);

 

// -- AND and NOT --

String expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";

boolean falseValue =parser.parseExpression(expression).getValue(societyContext, Boolean.class);

数学运算符如下:

// Addition

int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2

 

String testString = parser.parseExpression(

                "'test'+ ' ' + 'string'").getValue(String.class); // 'test string'

 

// Subtraction

int four = parser.parseExpression("1 - -3").getValue(Integer.class); // 4

 

double d = parser.parseExpression("1000.00 - 1e4").getValue(Double.class);// -9000

 

// Multiplication

int six = parser.parseExpression("-2 * -3").getValue(Integer.class); // 6

 

double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class);// 24.0

 

// Division

int minusTwo = parser.parseExpression("6 / -3").getValue(Integer.class); // -2

 

double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double.class);// 1.0

 

// Modulus

int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3

 

int one = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1

 

// Operator precedence

int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21

8.赋值

Inventor inventor = new Inventor();

StandardEvaluationContext inventorContext =newStandardEvaluationContext(inventor);

 

parser.parseExpression("Name").setValue(inventorContext, "Alexander Seovic2");

 

// alternatively

 

String aleks = parser.parseExpression(

                "Name= 'Alexandar Seovic'").getValue(inventorContext, String.class);

注意:getValuesetValue两种方法皆可。

9.类型

T运算符用于指定一个java.lang.Class实例,也用于调用静态方法。如下:

Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);

 

Class stringClass = parser.parseExpression("T(String)").getValue(Class.class);

 

boolean trueValue = parser.parseExpression(

                "T(java.math.RoundingMode).CEILING< T(java.math.RoundingMode).FLOOR")

                .getValue(Boolean.class);

10.构造方法

new运算符用于调用构造方法。如下:

Inventor einstein = p.parseExpression(

                "neworg.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")

                .getValue(Inventor.class);

 

//create new inventorinstance within add method of List

p.parseExpression(

                "Members.add(neworg.spring.samples.spel.inventor.Inventor(

                        'Albert Einstein','German'))").getValue(societyContext);

11.变量

变量使用setVaribles方法进行设置,使用#variableName进行引用。如下:

Inventor tesla = new Inventor("NikolaTesla", "Serbian");

StandardEvaluationContext context = new StandardEvaluationContext(tesla);

context.setVariable("newName", "MikeTesla");

 

parser.parseExpression("Name = #newName").getValue(context);

 

System.out.println(tesla.getName()) // "Mike Tesla"

预定义变量#this指向当前求值对象。预定义变量#root指向根上下文对象。如下:

// create an array ofintegers

List<Integer> primes = new ArrayList<Integer>();

primes.addAll(Arrays.asList(2,3,5,7,11,13,17));

 

// create parser and set variable'primes' as the array of integers

ExpressionParser parser = new SpelExpressionParser();

StandardEvaluationContext context = new StandardEvaluationContext();

context.setVariable("primes",primes);

 

// all prime numbers > 10from the list (using selection ?{...})

// evaluates to [11, 13, 17]

List<Integer> primesGreaterThanTen =(List<Integer>) parser.parseExpression(

                "#primes.?[#this>10]").getValue(context);

12.函数

你可以通过注册自定义函数来扩展SpEL。如下:

ExpressionParser parser = new SpelExpressionParser();

StandardEvaluationContext context = new StandardEvaluationContext();

 

context.registerFunction("reverseString",

       StringUtils.class.getDeclaredMethod("reverseString",new Class[] { String.class }));

 

String helloWorldReversed =parser.parseExpression(

       "#reverseString('hello')").getValue(context,String.class);

其中:

public abstract class StringUtils {

 

       public static String reverseString(String input) {

                StringBuilder backwards = new StringBuilder();

                for(int i = 0; i < input.length();i++)

                       backwards.append(input.charAt(input.length() - 1- i));

                }

                returnbackwards.toString();

       }

}

13.Bean引用

引用bean使用@符号,引用FactoryBean使用&符号。如下:

ExpressionParser parser = new SpelExpressionParser();

StandardEvaluationContext context = new StandardEvaluationContext();

context.setBeanResolver(new MyBeanResolver());

 

// This will end up callingresolve(context,"foo") on MyBeanResolver during evaluation

Object bean = parser.parseExpression("@foo").getValue(context);

 

// This will end up callingresolve(context,"&foo") on MyBeanResolver during evaluation

Object bean = parser.parseExpression("&foo").getValue(context);

14.三元运算符(If-Then-Else)

parser.parseExpression("Name").setValue(societyContext, "IEEE");

societyContext.setVariable("queryName", "NikolaTesla");

 

expression = "isMember(#queryName)?#queryName + ' is a member of the ' " +

                "+Name + ' Society' : #queryName + ' is not a member of the ' + Name + 'Society'";

 

String queryResultString =parser.parseExpression(expression)

                .getValue(societyContext,String.class);

// queryResultString ="Nikola Tesla is a member of the IEEE Society"

15. Elvis运算符

Elvis运算符比三元运算符更简短,来自于Groovy语言。如下:

ExpressionParser parser = new SpelExpressionParser();

 

Inventor tesla = new Inventor("Nikola Tesla","Serbian");

StandardEvaluationContext context = new StandardEvaluationContext(tesla);

 

String name = parser.parseExpression("Name?:'Elvis Presley'").getValue(context,String.class);

 

System.out.println(name); // Nikola Tesla

 

tesla.setName(null);

 

name = parser.parseExpression("Name?:'Elvis Presley'").getValue(context,String.class);

 

System.out.println(name); // Elvis Presley

注意:Elvis运算符可以用于@Value注解来指定默认值:

@Value("#{systemProperties['pop3.port'] ?: 25}")

16.安全导航运算符

安全导航运算符用于避免抛出NullPointException,只返回null。也来自于groovy语言,如下:

ExpressionParser parser = new SpelExpressionParser();

 

Inventor tesla = new Inventor("Nikola Tesla","Serbian");

tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan"));

 

StandardEvaluationContext context = new StandardEvaluationContext(tesla);

 

String city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, String.class);

System.out.println(city); // Smiljan

 

tesla.setPlaceOfBirth(null);

 

city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, String.class);

 

System.out.println(city); // null - does not throw NullPointerException!!!

17.集合选择

集合选择用于根据条件来过滤并返回新的子集合。例如:

List<Inventor> list = (List<Inventor>)parser.parseExpression(

                "Members.?[Nationality== 'Serbian']").getValue(societyContext);

 

Map newMap = parser.parseExpression("map.?[value<27]").getValue();

注意:可以使用^[…]$[…]语法来检索第一个和最后一个元素。

18.集合投影

投影的概念等价于关系数据库中投影概念。如下:

// returns ['Smiljan','Idvor' ]

List placesOfBirth = (List)parser.parseExpression("Members.![placeOfBirth.city]");

注意:投影也适用于Map,返回一个List

19.表达式模板

表达式模板允许字面值和求值块混合在一起,其中求值块通常使用#{}进行界定。如下:

String randomPhrase =parser.parseExpression(

                "randomnumber is #{T(java.lang.Math).random()}",

                newTemplateParserContext()).getValue(String.class);

 

// evaluates to "randomnumber is 0.7038186818312008"

其中:

public class TemplateParserContextimplements ParserContext {

 

       public String getExpressionPrefix() {

                return"#{";

       }

 

       public String getExpressionSuffix() {

                return"}";

       }

 

       public boolean isTemplate() {

                returntrue;

       }

}

阅读原文

为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权