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.context.expression;
018
019import org.springframework.beans.factory.config.BeanExpressionContext;
020import org.springframework.expression.AccessException;
021import org.springframework.expression.EvaluationContext;
022import org.springframework.expression.PropertyAccessor;
023import org.springframework.expression.TypedValue;
024import org.springframework.lang.Nullable;
025import org.springframework.util.Assert;
026
027/**
028 * EL property accessor that knows how to traverse the beans and contextual objects
029 * of a Spring {@link org.springframework.beans.factory.config.BeanExpressionContext}.
030 *
031 * @author Juergen Hoeller
032 * @author Andy Clement
033 * @since 3.0
034 */
035public class BeanExpressionContextAccessor implements PropertyAccessor {
036
037        @Override
038        public boolean canRead(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
039                return (target instanceof BeanExpressionContext && ((BeanExpressionContext) target).containsObject(name));
040        }
041
042        @Override
043        public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
044                Assert.state(target instanceof BeanExpressionContext, "Target must be of type BeanExpressionContext");
045                return new TypedValue(((BeanExpressionContext) target).getObject(name));
046        }
047
048        @Override
049        public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
050                return false;
051        }
052
053        @Override
054        public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue)
055                        throws AccessException {
056
057                throw new AccessException("Beans in a BeanFactory are read-only");
058        }
059
060        @Override
061        public Class<?>[] getSpecificTargetClasses() {
062                return new Class<?>[] {BeanExpressionContext.class};
063        }
064
065}