spel表达式运算使用

spel表达式运算使用

翻看公司代码,这一块不是很懂,查资料,记一下,还是太菜

1. 常用的对象

  • Expression: 表达式对象
  • SpelExpressionParser:表达式解析器
  • EvaluationContext:上下文

2. 使用

本文参考了下面的几篇文章

public class AccessingPropertiesApplication {
    static Logger logger = Logger.getLogger(AccessingPropertiesApplication.class);
    public static void main(String []args) {
        ExpressionParser parser = new SpelExpressionParser();
        //a. 调用String这个javaBean的'getBytes()'
        Expression exp = parser.parseExpression("'Hello World'.bytes");
        byte[] bytes = (byte[]) exp.getValue();
        logger.info("字节内容:"+ bytes);

        //b.嵌套的bean实例方法调用,通过'.'运算符
        exp = parser.parseExpression("'Hello World'.bytes.length");
        int len = (Integer) exp.getValue();
        logger.info("字节长度:" + len);

        //c. property訪問
        GregorianCalendar c = new GregorianCalendar();
        c.set(1856, 7, 9);
        //Inventor的构造函数参数分别是:name, birthday, and nationality.
        Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
        parser = new SpelExpressionParser();
        exp = parser.parseExpression("name");
        EvaluationContext context = new StandardEvaluationContext(tesla);
        String name = (String) exp.getValue(context);
        logger.info("Inventor: " + name);

        //对对象实例的成员进行操作。 evals to 1856, 注意纪年中,起点是从1900开始。
        int year = (Integer) parser.parseExpression("Birthdate.Year  + 1900").getValue(context);
        //Inventor tesla设置出生地(瞎写的信息)。
        tesla.setPlaceOfBirth(new PlaceOfBirth("America city", "America"));
        String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context);
        logger.info("year: " + year + ", city: " + city);

        //d. array, list操作
        // 先测试验证array
        tesla.setInventions(new String []{"交流点","交流电发电机","交流电变压器","变形记里面的缩小器"});
        EvaluationContext teslaContext = new StandardEvaluationContext(tesla);
        String invention = parser.parseExpression("inventions[3]").getValue(teslaContext, String.class);
        logger.info("Array: " + invention);
        //list测试验证
        Society society = new Society();
        society.addMember(tesla);
        StandardEvaluationContext societyContext = new StandardEvaluationContext(society);
        // evaluates to "Nikola Tesla"
        String mName = parser.parseExpression("Members[0].Name").getValue(societyContext, String.class);
        // List and Array navigation
        // evaluates to "Wireless communication"
        String mInvention = parser.parseExpression("Members[0].Inventions[2]").getValue(societyContext, String.class);
        logger.info("List: mName= " + mName + ", mInvention= " + mInvention);

        //e. Map的操作
        //首先构建数据环境
        GregorianCalendar cm = new GregorianCalendar();
        cm.set(1806, 7, 9);
        Inventor idv = new Inventor("Idovr", cm.getTime(), "China,haha");
        Society soc = new Society();
        idv.setPlaceOfBirth(new PlaceOfBirth("Wuhan","China"));
        soc.addOfficer(Advisors, idv);
        soc.addOfficer(President, tesla);
        EvaluationContext socCtxt = new StandardEvaluationContext(soc);
        Inventor pupin = parser.parseExpression("Officers['president']").getValue(socCtxt, Inventor.class);
        String mCity = parser.parseExpression("Officers['president'].PlaceOfBirth.City").getValue(socCtxt, String.class);
        logger.info("Map case 1: " + mCity);
        // setting values
        Expression mExp = parser.parseExpression("Officers['advisors'].PlaceOfBirth.Country");
        mExp.setValue(socCtxt, "Croatia");
        //下面注释掉的,是官方的做法,这个是有问题的,基于我的研究环境
        //parser.parseExpression("Officers['advisors'][0].PlaceOfBirth.Country").setValue(socCtxt, "Croatia");
        //String country = parser.parseExpression("Officers['advisors'][0].PlaceOfBirth.Country").getValue(socCtxt, String.class);
        String country = mExp.getValue(socCtxt, String.class);
        logger.info("Map case 2: " + country);
    }
}

3. 我自己的例子

  • 实体类
package com;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

@Data
public class A{
    private Integer id ;
    private String name ;
    private String ccc ;
    List<String> lists = new ArrayList<>(10);

    public A(Integer id, String name, String ccc) {
        this.id = id;
        this.name = name;
        this.ccc = ccc;
        IntStream.range(0,10).forEach(t->lists.add(String.valueOf(t)));
    }
    @Override
    public String toString() {
        return "A{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", list=" + ccc +
                '}';
    }
}
  • 校验类
   Expression  exp = null;
        SpelExpressionParser parser = null;
        A tesla = new A(1, "aaa","ccc");
        parser = new SpelExpressionParser();
        //属性名.方法或者属性
        exp = parser.parseExpression("lists.size() > 0");
        EvaluationContext context = new StandardEvaluationContext(tesla);
        /**
         * 这个 context 是上下文。
         * getValue(第一个是 context ,第二个是想要返回的值)这个值是可要可不要的. 不指定类型的话返回的就是 object了
         */
        Boolean value = exp.getValue(context, Boolean.class);
        int year = (Integer) parser.parseExpression("id  + 1900").getValue(context);
        logger.info("year,{}",year);
        logger.info("Inventor: " + value);

记一次错误

  • 报错信息为:
    maybe not public or not valid
  • 解决方式
    添加get和set方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值