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.core.env.Environment;
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 * Read-only EL property accessor that knows how to retrieve keys
029 * of a Spring {@link Environment} instance.
030 *
031 * @author Chris Beams
032 * @since 3.1
033 */
034public class EnvironmentAccessor implements PropertyAccessor {
035
036        @Override
037        public Class<?>[] getSpecificTargetClasses() {
038                return new Class<?>[] {Environment.class};
039        }
040
041        /**
042         * Can read any {@link Environment}, thus always returns true.
043         * @return true
044         */
045        @Override
046        public boolean canRead(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
047                return true;
048        }
049
050        /**
051         * Access the given target object by resolving the given property name against the given target
052         * environment.
053         */
054        @Override
055        public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
056                Assert.state(target instanceof Environment, "Target must be of type Environment");
057                return new TypedValue(((Environment) target).getProperty(name));
058        }
059
060        /**
061         * Read-only: returns {@code false}.
062         */
063        @Override
064        public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
065                return false;
066        }
067
068        /**
069         * Read-only: no-op.
070         */
071        @Override
072        public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue)
073                        throws AccessException {
074        }
075
076}