i'm new to Java, Spring and SpEL and i can't make this simple code work (it works without evaluation imports tho)
This is my 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}");
}
}
This is my 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);
}
}
Error: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
Any hints?
Thanks for your time.
Adjust the greeeting
method as follows. Notice that Integer.class
is passed to 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);
}
Then call with:
instance.greeting("5+5");