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.BeanFactory; 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 of a 029 * Spring {@link org.springframework.beans.factory.BeanFactory}. 030 * 031 * @author Juergen Hoeller 032 * @author Andy Clement 033 * @since 3.0 034 */ 035public class BeanFactoryAccessor implements PropertyAccessor { 036 037 @Override 038 public Class<?>[] getSpecificTargetClasses() { 039 return new Class<?>[] {BeanFactory.class}; 040 } 041 042 @Override 043 public boolean canRead(EvaluationContext context, @Nullable Object target, String name) throws AccessException { 044 return (target instanceof BeanFactory && ((BeanFactory) target).containsBean(name)); 045 } 046 047 @Override 048 public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { 049 Assert.state(target instanceof BeanFactory, "Target must be of type BeanFactory"); 050 return new TypedValue(((BeanFactory) target).getBean(name)); 051 } 052 053 @Override 054 public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) throws AccessException { 055 return false; 056 } 057 058 @Override 059 public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue) 060 throws AccessException { 061 062 throw new AccessException("Beans in a BeanFactory are read-only"); 063 } 064 065}