001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.expression.spel.ast; 018 019import org.springframework.expression.AccessException; 020import org.springframework.expression.BeanResolver; 021import org.springframework.expression.EvaluationException; 022import org.springframework.expression.TypedValue; 023import org.springframework.expression.spel.ExpressionState; 024import org.springframework.expression.spel.SpelEvaluationException; 025import org.springframework.expression.spel.SpelMessage; 026 027/** 028 * Represents a bean reference to a type, for example <tt>@foo</tt> or <tt>@'foo.bar'</tt>. 029 * For a FactoryBean the syntax <tt>&foo</tt> can be used to access the factory itself. 030 * 031 * @author Andy Clement 032 */ 033public class BeanReference extends SpelNodeImpl { 034 035 private final static String FACTORY_BEAN_PREFIX = "&"; 036 037 private final String beanName; 038 039 040 public BeanReference(int pos, String beanName) { 041 super(pos); 042 this.beanName = beanName; 043 } 044 045 046 @Override 047 public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { 048 BeanResolver beanResolver = state.getEvaluationContext().getBeanResolver(); 049 if (beanResolver == null) { 050 throw new SpelEvaluationException( 051 getStartPosition(), SpelMessage.NO_BEAN_RESOLVER_REGISTERED, this.beanName); 052 } 053 054 try { 055 return new TypedValue(beanResolver.resolve(state.getEvaluationContext(), this.beanName)); 056 } 057 catch (AccessException ex) { 058 throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION, 059 this.beanName, ex.getMessage()); 060 } 061 } 062 063 @Override 064 public String toStringAST() { 065 StringBuilder sb = new StringBuilder(); 066 if (!this.beanName.startsWith(FACTORY_BEAN_PREFIX)) { 067 sb.append("@"); 068 } 069 if (!this.beanName.contains(".")) { 070 sb.append(this.beanName); 071 } 072 else { 073 sb.append("'").append(this.beanName).append("'"); 074 } 075 return sb.toString(); 076 } 077 078}