spEL表達式,常用於註解中,將多樣的請求/響應對象轉換爲統一的對象。但是多樣的請求/響應對象會存在集合,我們如何通過spEL表達式去讀取集合的數據,或者是重寫請求/響應對象?
@Slf4j
public class ListSpELTest {
/**
* 觸發事件後,傳遞到aspect類的參數。
* <p>
* 格式:#{spEL}表達式
* 例如:#{#requestVo.name} 獲取請求對象requestVo中的name字段的值;
* #{#root.name} 獲取響應對象name字段的值
* #{{name:#requestVo.name,age:#root.age,type:'字符串'}} 組裝map對象
*/
public static void main(String[] args) {
spEL2FillList();
}
/**
* spEL表達式去填充list集合。
* 需要自定義一個規則
*/
private static void spEL2FillList() {
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext();
//解析模板#{}
TemplateParserContext parserContext = new TemplateParserContext();
User user = new User(1L, "tom",
Lists.newArrayList(new Info("xxx"), new Info("yyy")));
context.setVariable("user", user);
String value = "#{#user.infos[%d].url}";
String parseValue = StringUtils.substring(value, 0, value.indexOf("[%d]")) + "}";
if (!parseValue.equals(value)) {
List arrObj =
parser.parseExpression(parseValue, parserContext).getValue(context, List.class);
if (!CollectionUtils.isEmpty(arrObj)) {
for (int i = 0; i < arrObj.size(); i++) {
String format = String.format(value, i);
String oriVal = parser.parseExpression(format, parserContext)
.getValue(context, String.class);
log.info("原始集合的值:{}", oriVal);
//業務操作,重寫數據
String tarVal = oriVal + "-目標值";
parser.parseExpression(format, parserContext).setValue(context, tarVal);
}
}
}
System.out.println(user);
}
private static void spEL2Map() {
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext();
Account account = new Account("Deniro");
// User user = new User(1L, "tom",
// Lists.newArrayList(new Info("xxx"), new Info("yyy")));
User user = new User(1L, "tom", null);
//設置上下文對象
context.setVariable("account", account);
context.setVariable("user", user);
//將上下文對象轉換爲Map對象,支持三目表達式#user?.infos
Map<String, Object> objectMap =
(Map) parser.parseExpression("{acName:#account.name,userUrls:#user.infos?.![#this]}")
.getValue(context);
System.out.println(objectMap);
}
/**
* 獲取到集合的值
*/
private static void getListValue() {
Account account = new Account("Deniro");
ExpressionParser parser
= new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(account);
//將數據轉換成集合
List<Double> scores = new ArrayList<>();
scores.addAll(Arrays.asList(23.1, 82.3, 55.9));
context.setVariable("scores", scores);//在上下文中定義 scores 變量
List<Double> scoresGreat80 = (List<Double>) parser.parseExpression("#scores.?[#this>80]")
.getValue(context);
System.out.println(scoresGreat80);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Account {
private String name;
}
}