我是Java,Spring和SpEL的新手,我无法使这个简单的代码工作(它可以在没有评估导入的情况下工作)
这是我的Class 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}");
}
}
这是我的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({)'
任何提示?
感谢您的时间。
答案 0 :(得分:2)
按如下方式调整greeeting
方法。请注意,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");