官方文档中包含了多种用法,不再赘述:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-language-ref
值得注意的是:使用Spring EL表达式时,最好是提前将Expression创建,否则在大量使用时影响性能。
//初始化将Expression创建,放入指定的集合里即可,比如Map
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(mxjsyRule);
map.put("xxxxx", exp);
实际应用
在做活动营销、促销活动时,会涉及多种折扣计算,使用spel表达式来优化代码。 注意:案例只注重spel表达式的使用,业务逻辑纯属虚构!!!
场景1:商品特价折扣计算
商品价格实体
@Data
@NoArgsConstructor
static class GoodsBO {
private Long goodsId;
private BigDecimal retailPrice;
private BigDecimal fav;
}
定义计算规则
public static final String bargainPriceRule = "fav.divide(retailPrice, 4, T(java.math.RoundingMode).HALF_UP)";
public static final String bargainPriceRule = "fav?.divide(retailPrice?:new java.math.BigDecimal('1'), 4, T(java.math.RoundingMode).HALF_UP)";
public static final String bargainPriceRule = "fav / retailPrice";
业务处理
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(bargainPriceRule);
GoodsBO goodsBO = new GoodsBO();
goodsBO.setGoodsId(1L);
goodsBO.setRetailPrice(new BigDecimal("10.2"));
goodsBO.setFav(new BigDecimal("9"));
BigDecimal calcResult = exp.getValue(goodsBO, BigDecimal.class);
System.out.println(calcResult);
}
场景2:商品满赠折扣计算
商品价格实体
@Data
@NoArgsConstructor
static class GoodsBO {
private Long goodsId;
private BigDecimal retailPrice;
private BigDecimal threshold;
private BigDecimal fav;
private BigDecimal giftCount;
private BigDecimal giftMaxPrice;
}
定义计算规则
public static final String mxjsyRule = "retailPrice.multiply(giftCount).divide(threshold.multiply(retailPrice.multiply(giftCount).add(giftMaxPrice)), 4, T(java.math.RoundingMode).HALF_UP)";
业务处理
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(mxjsyRule);
GoodsBO goodsBO = new GoodsBO();
goodsBO.setGoodsId(1L);
goodsBO.setRetailPrice(new BigDecimal("10.2"));
goodsBO.setFav(new BigDecimal("9"));
goodsBO.setGiftCount(new BigDecimal("5"));
goodsBO.setThreshold(new BigDecimal("3"));
goodsBO.setGiftMaxPrice(new BigDecimal("20.5"));
BigDecimal calcResult = exp.getValue(goodsBO, BigDecimal.class);
System.out.println(calcResult);
}
场景3:@Value读取配置
在读取配置时候,可指定默认值,条件判断等多种操作
@Value("${testValue?:'赋默认值'}")
private String testValue;
@Value("${testValue == 100}")
private Boolean testValue;
|