001/*
002 * Copyright 2002-2018 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.beans.factory.annotation;
018
019import java.beans.PropertyDescriptor;
020import java.lang.annotation.Annotation;
021import java.lang.reflect.Method;
022import java.util.ArrayList;
023import java.util.Collections;
024import java.util.List;
025import java.util.Set;
026import java.util.concurrent.ConcurrentHashMap;
027
028import org.springframework.beans.BeansException;
029import org.springframework.beans.PropertyValues;
030import org.springframework.beans.factory.BeanFactory;
031import org.springframework.beans.factory.BeanFactoryAware;
032import org.springframework.beans.factory.BeanInitializationException;
033import org.springframework.beans.factory.config.BeanDefinition;
034import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
035import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
036import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
037import org.springframework.beans.factory.support.RootBeanDefinition;
038import org.springframework.core.Conventions;
039import org.springframework.core.Ordered;
040import org.springframework.core.PriorityOrdered;
041import org.springframework.core.annotation.AnnotationUtils;
042import org.springframework.util.Assert;
043
044/**
045 * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
046 * that enforces required JavaBean properties to have been configured.
047 * Required bean properties are detected through a Java 5 annotation:
048 * by default, Spring's {@link Required} annotation.
049 *
050 * <p>The motivation for the existence of this BeanPostProcessor is to allow
051 * developers to annotate the setter properties of their own classes with an
052 * arbitrary JDK 1.5 annotation to indicate that the container must check
053 * for the configuration of a dependency injected value. This neatly pushes
054 * responsibility for such checking onto the container (where it arguably belongs),
055 * and obviates the need (<b>in part</b>) for a developer to code a method that
056 * simply checks that all required properties have actually been set.
057 *
058 * <p>Please note that an 'init' method may still need to be implemented (and may
059 * still be desirable), because all that this class does is enforcing that a
060 * 'required' property has actually been configured with a value. It does
061 * <b>not</b> check anything else... In particular, it does not check that a
062 * configured value is not {@code null}.
063 *
064 * <p>Note: A default RequiredAnnotationBeanPostProcessor will be registered
065 * by the "context:annotation-config" and "context:component-scan" XML tags.
066 * Remove or turn off the default annotation configuration there if you intend
067 * to specify a custom RequiredAnnotationBeanPostProcessor bean definition.
068 *
069 * @author Rob Harrop
070 * @author Juergen Hoeller
071 * @since 2.0
072 * @see #setRequiredAnnotationType
073 * @see Required
074 */
075public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
076                implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
077
078        /**
079         * Bean definition attribute that may indicate whether a given bean is supposed
080         * to be skipped when performing this post-processor's required property check.
081         * @see #shouldSkip
082         */
083        public static final String SKIP_REQUIRED_CHECK_ATTRIBUTE =
084                        Conventions.getQualifiedAttributeName(RequiredAnnotationBeanPostProcessor.class, "skipRequiredCheck");
085
086
087        private Class<? extends Annotation> requiredAnnotationType = Required.class;
088
089        private int order = Ordered.LOWEST_PRECEDENCE - 1;
090
091        private ConfigurableListableBeanFactory beanFactory;
092
093        /**
094         * Cache for validated bean names, skipping re-validation for the same bean
095         */
096        private final Set<String> validatedBeanNames =
097                        Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(64));
098
099
100        /**
101         * Set the 'required' annotation type, to be used on bean property
102         * setter methods.
103         * <p>The default required annotation type is the Spring-provided
104         * {@link Required} annotation.
105         * <p>This setter property exists so that developers can provide their own
106         * (non-Spring-specific) annotation type to indicate that a property value
107         * is required.
108         */
109        public void setRequiredAnnotationType(Class<? extends Annotation> requiredAnnotationType) {
110                Assert.notNull(requiredAnnotationType, "'requiredAnnotationType' must not be null");
111                this.requiredAnnotationType = requiredAnnotationType;
112        }
113
114        /**
115         * Return the 'required' annotation type.
116         */
117        protected Class<? extends Annotation> getRequiredAnnotationType() {
118                return this.requiredAnnotationType;
119        }
120
121        @Override
122        public void setBeanFactory(BeanFactory beanFactory) {
123                if (beanFactory instanceof ConfigurableListableBeanFactory) {
124                        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
125                }
126        }
127
128        public void setOrder(int order) {
129                this.order = order;
130        }
131
132        @Override
133        public int getOrder() {
134                return this.order;
135        }
136
137
138        @Override
139        public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
140        }
141
142        @Override
143        public PropertyValues postProcessPropertyValues(
144                        PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
145
146                if (!this.validatedBeanNames.contains(beanName)) {
147                        if (!shouldSkip(this.beanFactory, beanName)) {
148                                List<String> invalidProperties = new ArrayList<String>();
149                                for (PropertyDescriptor pd : pds) {
150                                        if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) {
151                                                invalidProperties.add(pd.getName());
152                                        }
153                                }
154                                if (!invalidProperties.isEmpty()) {
155                                        throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName));
156                                }
157                        }
158                        this.validatedBeanNames.add(beanName);
159                }
160                return pvs;
161        }
162
163        /**
164         * Check whether the given bean definition is not subject to the annotation-based
165         * required property check as performed by this post-processor.
166         * <p>The default implementations check for the presence of the
167         * {@link #SKIP_REQUIRED_CHECK_ATTRIBUTE} attribute in the bean definition, if any.
168         * It also suggests skipping in case of a bean definition with a "factory-bean"
169         * reference set, assuming that instance-based factories pre-populate the bean.
170         * @param beanFactory the BeanFactory to check against
171         * @param beanName the name of the bean to check against
172         * @return {@code true} to skip the bean; {@code false} to process it
173         */
174        protected boolean shouldSkip(ConfigurableListableBeanFactory beanFactory, String beanName) {
175                if (beanFactory == null || !beanFactory.containsBeanDefinition(beanName)) {
176                        return false;
177                }
178                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
179                if (beanDefinition.getFactoryBeanName() != null) {
180                        return true;
181                }
182                Object value = beanDefinition.getAttribute(SKIP_REQUIRED_CHECK_ATTRIBUTE);
183                return (value != null && (Boolean.TRUE.equals(value) || Boolean.valueOf(value.toString())));
184        }
185
186        /**
187         * Is the supplied property required to have a value (that is, to be dependency-injected)?
188         * <p>This implementation looks for the existence of a
189         * {@link #setRequiredAnnotationType "required" annotation}
190         * on the supplied {@link PropertyDescriptor property}.
191         * @param propertyDescriptor the target PropertyDescriptor (never {@code null})
192         * @return {@code true} if the supplied property has been marked as being required;
193         * {@code false} if not, or if the supplied property does not have a setter method
194         */
195        protected boolean isRequiredProperty(PropertyDescriptor propertyDescriptor) {
196                Method setter = propertyDescriptor.getWriteMethod();
197                return (setter != null && AnnotationUtils.getAnnotation(setter, getRequiredAnnotationType()) != null);
198        }
199
200        /**
201         * Build an exception message for the given list of invalid properties.
202         * @param invalidProperties the list of names of invalid properties
203         * @param beanName the name of the bean
204         * @return the exception message
205         */
206        private String buildExceptionMessage(List<String> invalidProperties, String beanName) {
207                int size = invalidProperties.size();
208                StringBuilder sb = new StringBuilder();
209                sb.append(size == 1 ? "Property" : "Properties");
210                for (int i = 0; i < size; i++) {
211                        String propertyName = invalidProperties.get(i);
212                        if (i > 0) {
213                                if (i == (size - 1)) {
214                                        sb.append(" and");
215                                }
216                                else {
217                                        sb.append(",");
218                                }
219                        }
220                        sb.append(" '").append(propertyName).append("'");
221                }
222                sb.append(size == 1 ? " is" : " are");
223                sb.append(" required for bean '").append(beanName).append("'");
224                return sb.toString();
225        }
226
227}