gpt4 book ai didi

java - Spring SpEL 错误

转载 作者:行者123 更新时间:2023-11-30 04:08:21 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com