View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.expression.spel.ast;
18  
19  import org.springframework.expression.AccessException;
20  import org.springframework.expression.BeanResolver;
21  import org.springframework.expression.EvaluationException;
22  import org.springframework.expression.TypedValue;
23  import org.springframework.expression.spel.ExpressionState;
24  import org.springframework.expression.spel.SpelEvaluationException;
25  import org.springframework.expression.spel.SpelMessage;
26  
27  /**
28   * Represents a bean reference to a type, for example "@foo" or "@'foo.bar'"
29   *
30   * @author Andy Clement
31   */
32  public class BeanReference extends SpelNodeImpl {
33  
34  	private final String beanName;
35  
36  
37  	public BeanReference(int pos,String beanName) {
38  		super(pos);
39  		this.beanName = beanName;
40  	}
41  
42  
43  	@Override
44  	public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
45  		BeanResolver beanResolver = state.getEvaluationContext().getBeanResolver();
46  		if (beanResolver == null) {
47  			throw new SpelEvaluationException(
48  					getStartPosition(), SpelMessage.NO_BEAN_RESOLVER_REGISTERED, this.beanName);
49  		}
50  
51  		try {
52  			return new TypedValue(beanResolver.resolve(state.getEvaluationContext(), this.beanName));
53  		}
54  		catch (AccessException ex) {
55  			throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION,
56  				this.beanName, ex.getMessage());
57  		}
58  	}
59  
60  	@Override
61  	public String toStringAST() {
62  		StringBuilder sb = new StringBuilder("@");
63  		if (!this.beanName.contains(".")) {
64  			sb.append(this.beanName);
65  		}
66  		else {
67  			sb.append("'").append(this.beanName).append("'");
68  		}
69  		return sb.toString();
70  	}
71  
72  }