Bean Reference
The Spring Expression Language (SpEL ) is a simple and powerful expression language
which helps to query and manipulate objects at runtime.
SpEL allows us to perform customized lookup based on bean name.
We can configure a bean resolver with evaluation context
and perform lookup for all beans with (@ ) symbol as name prefix.
package com.bethecoder.tutorials.spring3.tests.spel;
import java.util.Random;
import org.springframework.expression.AccessException;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.bethecoder.tutorials.spring3.basic.Employee;
public class BeanReferenceTest {
/**
* @param args
*/
public static void main ( String [] args ) {
StandardEvaluationContext stdContext = new StandardEvaluationContext () ;
stdContext.setBeanResolver ( new SimpleBeanResolver ()) ;
ExpressionParser parser = new SpelExpressionParser () ;
// Invokes resolve(context, "one") on SimpleBeanResolver during evaluation
Employee emp = parser.parseExpression ( "@one" ) .getValue ( stdContext, Employee. class ) ;
System.out.println ( emp ) ;
// Invokes resolve(context, "two") on SimpleBeanResolver during evaluation
emp = parser.parseExpression ( "@two" ) .getValue ( stdContext, Employee. class ) ;
System.out.println ( emp ) ;
// Invokes resolve(context, "three") on SimpleBeanResolver during evaluation
emp = parser.parseExpression ( "@three" ) .getValue ( stdContext, Employee. class ) ;
System.out.println ( emp ) ;
}
}
class SimpleBeanResolver implements BeanResolver {
private static Random RAND = new Random () ;
@Override
public Object resolve (
EvaluationContext context,
String beanName ) throws AccessException {
int id = Math.abs ( RAND.nextInt ( 100 )) ;
double salary = RAND.nextDouble () * 10000 ;
Employee emp = new Employee ( id, beanName.toUpperCase () , salary ) ;
return emp;
}
}
It gives the following output,
Employee[43, ONE, 5564.5790815718]
Employee[97, TWO, 461.7049866801448]
Employee[51, THREE, 770.0703889044469]