tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > Expression Language > Bean Reference

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.

File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
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 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);

    // Invokes resolve(context, "two") on SimpleBeanResolver during evaluation
    emp = parser.parseExpression("@two").getValue(stdContext, Employee.class);
    // Invokes resolve(context, "three") on SimpleBeanResolver during evaluation
    emp = parser.parseExpression("@three").getValue(stdContext, Employee.class);



class SimpleBeanResolver implements BeanResolver {

  private static Random RAND = new Random();
  public Object resolve(
      EvaluationContext context,
      String beanNamethrows 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]


bl  br