/**
* @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);
- 空白目錄
- 0.環境準備
- 0.1基于maven的工程創建
- 1.控制反轉容器
- 1.1 Spring控制反轉容器和beans介紹
- 1.2 容器概覽
- 1.3 Bean概覽
- 1.4 依賴
- 1.5 Bean的范圍
- 1.6 客制bean的特性
- 1.7 Bean定義的繼承
- 1.8 容器擴展點
- 1.9 基于注解的容器配置
- 1.10 類路徑掃描及組件管理
- 1.11 使用JSR 330標準的注解
- 1.12 基于Java的容器配置
- 1.12.1 基本概念: @Bean 和 @Configuration
- 1.13 環境抽象化
- 1.14 注冊一個LoadTimeWeaver
- 1.15 ApplicationContext的附加功能
- 1.16 BeanFactory
- 2. 資源
- 3. 驗證,數據綁定和類型轉換
- 4. Spring表達式語言(SpEL)
- 5. Spring面向方面的切面編程
- 6. Spring AOP 接口
- 7. 空安全
- 8. 數據緩沖和編碼
- 9. 附錄