java - Spring SpEL 错误

标签 java spring spring-el

我是 Java、Spring 和 SpEL 新手,我无法使这个简单的代码工作(它无需评估导入即可工作)

这是我的类 RunSpring.java:

package run;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import helloworld.HelloSpringWorld;

public class RunSpring
{
    public static void main(String[] args)
    {
        //App Context
        ApplicationContext appContext = new ClassPathXmlApplicationContext("bean-data.xml");
        BeanFactory beanFactory = appContext;
        HelloSpringWorld instance = (HelloSpringWorld);
        beanFactory.getBean("helloSpringWorld");

        //Expression to be evaluated
        instance.greeting("${5+5}");
    }
}

这是我的类(class)HelloSpringWorld:

package helloworld;

import org.springframework.stereotype.Service;
//Expression imports
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;

@Service
public class HelloSpringWorld
{
    public void greeting(String name)
    {
        //Expression Setup
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression(name);
        String message = (String) exp.getValue();

        System.out.println("Hello and welcome to Spring: " + message);
    }
}

错误:解析有效表达式后,表达式中仍有更多数据:'lcurly({)'

有什么提示吗?

感谢您的宝贵时间。

最佳答案

如下调整greeting方法。请注意,Integer.class 被传递给 getValue()

public void greeting(String name)
{
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(name);
    String message = exp.getValue(Integer.class).toString();

    System.out.println("Hello and welcome to Spring: " + message);
}

然后调用:

instance.greeting("5+5");

关于java - Spring SpEL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225502/

相关文章:

java - 用于 Spring 安全的 SpEL : Passing Values from XML to Java based SpEL configuration

java - :remove is not working 内的 hasRole()

java - 如何从给定的对串中对具有共同边的节点进行分组?

java - OKHTTP3 POST FORM Android 应用程序不会将任何内容发布到 Google Forms

java - 使用注释将 JSF 请求参数注入(inject)到由 Spring 管理的 bean 中

java - Spring Boot 禁用 Redis 服务器

java - 当 ID 或任何属性中不存在值时,如何在 Selenium WebDriver 中使用 Java 从禁用的文本字段获取值

javascript - 验证后开始方法执行

java - Spring Batch ItemWriter Java

spring-el - 如何为多个系统属性执行多个逻辑结束?