spel表达式的用法_el表达式判断是否为空

spel表达式的用法_el表达式判断是否为空spel表达式运算使用翻看公司代码,这一块不是很懂,查资料,记一下,还是太菜1.常用的对象Expression:表达式对象SpelExpressionParser:表达式解析器EvaluationContext:上下文2.使用本文参考了下面的几篇文章https://www.cnblogs.com/shihuc/p/9338173.htmlhttps://blog.csdn.net/f641385712/article/details/90812967下面的例子主要是来源于第一

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

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方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197325.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Matlab画图常用的符号和颜色

    Matlab画图常用的符号和颜色

    2022年5月6日
    40
  • 常用电容分类_电容电阻

    常用电容分类_电容电阻一、瓷介电容器(CC)1.结构用陶瓷材料作介质,在陶瓷表面涂覆一层金属(银)薄膜,再经高温烧结后作为电极而成。瓷介电容器又分1类电介质(NPO、CCG));2类电介质(X7R、2X1)和3类电介质(Y5V、2F4)瓷介电容器。2.特点1类瓷介电容器具有温度系数小、稳定性高、损耗低、耐压高等优点。最大容量不超过1000pF,常用的有CC1、…

    2022年8月22日
    12
  • 自然语言处理真实项目实战(20170822)

    自然语言处理真实项目实战(20170822)

    2022年3月6日
    46
  • C++创建线程_C语言网络编程创建线程

    C++创建线程_C语言网络编程创建线程在window系统中编写控制台程序,创建线程使用CreateThread()函数创建,则线程函数必须申明为DWORDWINAPI;使用_beginthreadex()创建,则线程函数必须申明为unsignedintWINAPI;并需要设置环境:工程->设置->C/C++->CodeGeneration->Userun-timelibray->选DebugMultithr

    2022年8月30日
    3
  • navicat连接MySQL失败,cmd也不能登录MySQL_远程连接mysql

    navicat连接MySQL失败,cmd也不能登录MySQL_远程连接mysql出现Clientdoesnotsupportauthenticationprotocolrequestedbyserver…的解决方案mysqladmin-uroot-ppassword123456qmysql-uroot-pALTERUSER’root’@’localhost’IDENTIFIEDWITHmysql_native_password…

    2022年10月14日
    8
  • sm羞耻任务_羞耻驱动的发展

    sm羞耻任务_羞耻驱动的发展sm羞耻任务我一直渴望写出精巧的代码。在完成所有生产代码配对的日常工作中,我认为我们的质量很高。但是令人惊讶的是,当您独自编码时,您多么容易原谅自己并陷入不良习惯。配对时羞耻是品质背后的动力吗?我们有许多使用EasyMock编写的古老的单元测试;我们所有最近的单元测试都使用JMock。这笔小小的技术债务意味着,如果您要更改仅适用于EasyMock测试的代码,则首先必须决…

    2025年11月27日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号