💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
/** * @Title: MainTest.java * @Package com.oscar999.spel * @Description: TODO * @author oscar999 * @date Sep 3, 2018 5:25:54 PM * @version V1.0 */ package com.oscar999.spel; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; /** * @ClassName: MainTest * @Description: TODO * @author oscar999 */ public class MainTest { /** * @Title: main * @Description: TODO * @param args */ public static void main(String[] args) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("'Hello world'.concat('!')"); String message =(String) exp.getValue(); System.out.println(message); } } 4.2.1 EvaluationContext EvaluationContext接口用于评估表达式解决属性、方法或字段, 以及帮助类型转换, 有两个开箱即用的实现: - SimpleEvaluationContext  - StandardEvaluationContext 类型转换 4.2.2 解析器配置 4.2.3 SpEL编译 org.springframework.expression.spel.SpelCompilerMode -OFF 关闭, 默认 -IMMEDIATE -MIXED SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader()); S SpelExpressionParser parser = new SpelExpressionParser(config); Expression expr = parser.parseExpression("payload"); M MyMessage message = new MyMessage(); Object payload = expr.getValue(message); 4.3 bean定义中的表达式 4.3.1 XML配置 <bean id="numberGuess" class="org.spring.samples.NumberGuess"> <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/> <!-- other properties --> </bean> 4.3.2 注解配置 public static class FieldValueTestBean @Value("#{ systemProperties['user.region'] }") private String defaultLocale; public void setDefaultLocale(String defaultLocale) { this.defaultLocale = defaultLocale; } public String getDefaultLocale() { return this.defaultLocale; } } } public class SimpleMovieLister { private MovieFinder movieFinder; private String defaultLocale; @Autowired public void configure(MovieFinder movieFinder, @Value("#{ systemProperties['user.region'] }") String defaultLocale) { this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } // ... } } 4.4 语言参考 4.4.1 文字表达 ExpressionParser parser = new SpelExpressionParser(); // evals to "Hello World" String helloWorld = (String) parser.parseExpression("'Hello World'").getValue(); double avogadrosNumber = (Double) parser.parseExpression("6.0221415E+23").getValue(); // evals to 2147483647 int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue(); boolean trueValue = (Boolean) parser.parseExpression("true").getValue(); Object nullValue = parser.parseExpression("null").getValue(); 4.4.2 属性,Arrays, Lists, Maps , Indexers int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context); String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context); 4.4.3 内联列表, 使用 {}语法。 List numbers = (List) parser.parseExpression("{1,2,3,4}").getValue(context); List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(context); 4.4.4 内联Maps {key:value} 语法 Map inventorInfo = (Map) parser.parseExpression("{name:'Nikola',dob:'10-July-1856'}").getValue(context); Map mapOfMaps = (Map) parser.parseExpression("{name:{first:'Nikola',last:'Tesla'},dob:{day:10,month:'July',year:1856}}").getValue(context); 4.4.5 数组构造 int[] numbers1 = (int[]) parser.parseExpression("new int[4]").getValue(context); 4.4.6 方法 String bc = parser.parseExpression("'abc'.substring(1, 3)").getValue(String.class); boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue( societyContext, Boolean.class); 4.4.7 运算符 - 关系预算符 boolean trueValue = parser.parseExpression("2 == 2").getValue(Boolean.class); boolean falseValue = parser.parseExpression("2 < -5.0").getValue(Boolean.class); 匹配 boolean falseValue = parser.parseExpression( "'xyz' instanceof T(Integer)").getValue(Boolean.class); boolean trueValue = parser.parseExpression( "'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class); - 逻辑运算符 boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class); String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')"; boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class); -数学运算符 int two = parser.parseExpression("1 + 1").getValue(Integer.class); String testString = parser.parseExpression( "'test' + ' ' + 'string'").getValue(String.class); 4.4.8 Assignment Inventor inventor = new Inventor(); E EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build(); p parser.parseExpression("Name").setValue(context, inventor, "Aleksandar Seovic"); // alternatively String aleks = parser.parseExpression( "Name = 'Aleksandar Seovic'").getValue(context, inventor, String.class); 4.4.9 类型 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); 4.4.10 构造 器 Inventor einstein = p.parseExpression( "new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')") .getValue(Inventor.class); //create new inventor instance within add method of List p p.parseExpression( "Members.add(new org.spring.samples.spel.inventor.Inventor( 'Albert Einstein', 'German'))").getValue(societyContext); 4.4.11 变量 Inventor tesla = new Inventor("Nikola Tesla", "Serbian"); E EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build(); c context.setVariable("newName", "Mike Tesla"); p parser.parseExpression("Name = #newName").getValue(context, tesla); System.out.println(tesla.getName()) // "Mike Tesla" 4.4.12 函数 EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build(); c context.setVariable("myFunction", method); public abstract class StringUtils { public static String reverseString(String input) { StringBuilder backwards = new StringBuilder(input.length()); for (int i = 0; i < input.length(); i++) backwards.append(input.charAt(input.length() - 1 - i)); } return backwards.toString(); } } } ExpressionParser parser = new SpelExpressionParser(); E EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build(); c context.setVariable("reverseString", StringUtils.class.getDeclaredMethod("reverseString", String.class)); String helloWorldReversed = parser.parseExpression( "#reverseString('hello')").getValue(context, String.class); 4.4.13 Bean 引用 ExpressionParser parser = new SpelExpressionParser(); S StandardEvaluationContext context = new StandardEvaluationContext(); c context.setBeanResolver(new MyBeanResolver()); // This will end up calling resolve(context,"foo") on MyBeanResolver during evaluation Object bean = parser.parseExpression("@foo").getValue(context); 4.4.14 三元运算符 If-Then-Else String falseString = parser.parseExpression( "false ? 'trueExp' : 'falseExp'").getValue(String.class); parser.parseExpression("Name").setValue(societyContext, "IEEE"); s societyContext.setVariable("queryName", "Nikola Tesla"); e 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); 4.4.15 Elvis 运算符 ExpressionParser parser = new SpelExpressionParser(); String name = parser.parseExpression("name?:'Unknown'").getValue(String.class); System.out.println(name); // 'Unknown' 4.4.16 安全导航运算符 来自Groovy语言,避免空指针异常NullPointerException 。 ExpressionParser parser = new SpelExpressionParser(); E EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build(); I Inventor tesla = new Inventor("Nikola Tesla", "Serbian"); t tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan")); String city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, tesla, String.class); System.out.println(city); // Smiljan t tesla.setPlaceOfBirth(null); c city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, tesla, String.class); System.out.println(city); // null - does not throw NullPointerException!!! 4.4.17 Collection选择 List<Inventor> list = (List<Inventor>) parser.parseExpression( "Members.?[Nationality == 'Serbian']").getValue(societyContext); 4.4.18 Collection Projection List placesOfBirth = (List)parser.parseExpression("Members.![placeOfBirth.city]"); 4.4.19 表达式模板 String randomPhrase = parser.parseExpression( "random number is #{T(java.lang.Math).random()}", new TemplateParserContext()).getValue(String.class);