需求:输出一个字符串内容,要求所有部分支持灵活配置
格式如下:
- 99|@流水号|@店代码|@金额。
- 其中99和符号|是固定值.@流水号、@店代码、@金额是变量
解决方案:
利用SPEL表达式灵活配置解析字符串模板内容
核心代码:
- import org.springframework.expression.EvaluationContext;
- import org.springframework.expression.Expression;
- import org.springframework.expression.ExpressionParser;
- import org.springframework.expression.spel.standard.SpelExpressionParser;
- import org.springframework.expression.spel.support.StandardEvaluationContext;
- import java.util.Objects;
- /**
- * Description: SPEL表达式处理工具
- * Created by Hoscen on 2021/4/23 9:49
- */
- public class SpelUtil {
- private SpelUtil() {
- }
- /**
- * 解析模板中的表达式并转换
- * Created by Hoscen on 2021/4/23 12:01
- * @param expTemplateContent 含有表达式的字符串,例:('99').concat('|').concat(#saleHead.sequence)
- * @param obj 数据对象 , 例:SaleHead saleHead = SaleHead.builder().sequence(100L).build();
- * @param objName 数据对象在表达式中使用的实例名 ,例:saleHead
- * @return java.lang.String
- */
- public static String parseExpressionContent(String expTemplateContent, Object obj, String objName) {
- ExpressionParser parser = new SpelExpressionParser();
- String value = "";
- try {
- Expression expression = parser.parseExpression(expTemplateContent);
- EvaluationContext context = new StandardEvaluationContext();
- context.setVariable(objName, obj);
- value = Objects.requireNonNull(expression.getValue(context)).toString();
- } catch (Exception e) {
- if (e instanceof NullPointerException) {
- throw new ExpressionContentException("数据对象" + objName + "[" + JSON.toJSONString(obj) + "]异常", e);
- } else {
- throw new ExpressionContentException("表达式配置内容[" + expTemplateContent + "]异常", e);
- }
- }
- return value;
- }
- /*public static void main(String[] args) {
- SaleHead saleHead = SaleHead.builder().sequence(100L).storeId("10010").amount(123545.51D).build();
- String expTemplateContent = "('99').concat('|').concat(#saleHead.sequence).concat('|').concat(#saleHead.storeId).concat('|').concat(#saleHead.amount)";
- System.out.println(SpelUtil.parseExpressionContent(expTemplateContent, saleHead, "saleHead"));
- }*/
- }
- /**
- * Description: 表达式内容异常
- * Created by Hoscen on 2021/4/23 9:15
- */
- public class ExpressionContentException extends RuntimeException{
- public ExpressionContentException(String message, Throwable cause) {
- super(message, cause);
- }
- }