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.PropertyValues;
029import org.springframework.beans.factory.BeanFactory;
030import org.springframework.beans.factory.BeanFactoryAware;
031import org.springframework.beans.factory.BeanInitializationException;
032import org.springframework.beans.factory.config.BeanDefinition;
033import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
034import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
035import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
036import org.springframework.beans.factory.support.RootBeanDefinition;
037import org.springframework.core.Conventions;
038import org.springframework.core.Ordered;
039import org.springframework.core.PriorityOrdered;
040import org.springframework.core.annotation.AnnotationUtils;
041import org.springframework.lang.Nullable;
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 * @deprecated as of 5.1, in favor of using constructor injection for required settings
075 * (or a custom {@link org.springframework.beans.factory.InitializingBean} implementation)
076 */
077@Deprecated
078public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
079                implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
080
081        /**
082         * Bean definition attribute that may indicate whether a given bean is supposed
083         * to be skipped when performing this post-processor's required property check.
084         * @see #shouldSkip
085         */
086        public static final String SKIP_REQUIRED_CHECK_ATTRIBUTE =
087                        Conventions.getQualifiedAttributeName(RequiredAnnotationBeanPostProcessor.class, "skipRequiredCheck");
088
089
090        private Class<? extends Annotation> requiredAnnotationType = Required.class;
091
092        private int order = Ordered.LOWEST_PRECEDENCE - 1;
093
094        @Nullable
095        private ConfigurableListableBeanFactory beanFactory;
096
097        /**
098         * Cache for validated bean names, skipping re-validation for the same bean.
099         */
100        private final Set<String> validatedBeanNames = Collections.newSetFromMap(new ConcurrentHashMap<>(64));
101
102
103        /**
104         * Set the 'required' annotation type, to be used on bean property
105         * setter methods.
106         * <p>The default required annotation type is the Spring-provided
107         * {@link Required} annotation.
108         * <p>This setter property exists so that developers can provide their own
109         * (non-Spring-specific) annotation type to indicate that a property value
110         * is required.
111         */
112        public void setRequiredAnnotationType(Class<? extends Annotation> requiredAnnotationType) {
113                Assert.notNull(requiredAnnotationType, "'requiredAnnotationType' must not be null");
114                this.requiredAnnotationType = requiredAnnotationType;
115        }
116
117        /**
118         * Return the 'required' annotation type.
119         */
120        protected Class<? extends Annotation> getRequiredAnnotationType() {
121                return this.requiredAnnotationType;
122        }
123
124        @Override
125        public void setBeanFactory(BeanFactory beanFactory) {
126                if (beanFactory instanceof ConfigurableListableBeanFactory) {
127                        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
128                }
129        }
130
131        public void setOrder(int order) {
132                this.order = order;
133        }
134
135        @Override
136        public int getOrder() {
137                return this.order;
138        }
139
140
141        @Override
142        public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
143        }
144
145        @Override
146        public PropertyValues postProcessPropertyValues(
147                        PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
148
149                if (!this.validatedBeanNames.contains(beanName)) {
150                        if (!shouldSkip(this.beanFactory, beanName)) {
151                                List<String> invalidProperties = new ArrayList<>();
152                                for (PropertyDescriptor pd : pds) {
153                                        if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) {
154                                                invalidProperties.add(pd.getName());
155                                        }
156                                }
157                                if (!invalidProperties.isEmpty()) {
158                                        throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName));
159                                }
160                        }
161                        this.validatedBeanNames.add(beanName);
162                }
163                return pvs;
164        }
165
166        /**
167         * Check whether the given bean definition is not subject to the annotation-based
168         * required property check as performed by this post-processor.
169         * <p>The default implementations check for the presence of the
170         * {@link #SKIP_REQUIRED_CHECK_ATTRIBUTE} attribute in the bean definition, if any.
171         * It also suggests skipping in case of a bean definition with a "factory-bean"
172         * reference set, assuming that instance-based factories pre-populate the bean.
173         * @param beanFactory the BeanFactory to check against
174         * @param beanName the name of the bean to check against
175         * @return {@code true} to skip the bean; {@code false} to process it
176         */
177        protected boolean shouldSkip(@Nullable ConfigurableListableBeanFactory beanFactory, String beanName) {
178                if (beanFactory == null || !beanFactory.containsBeanDefinition(beanName)) {
179                        return false;
180                }
181                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
182                if (beanDefinition.getFactoryBeanName() != null) {
183                        return true;
184                }
185                Object value = beanDefinition.getAttribute(SKIP_REQUIRED_CHECK_ATTRIBUTE);
186                return (value != null && (Boolean.TRUE.equals(value) || Boolean.parseBoolean(value.toString())));
187        }
188
189        /**
190         * Is the supplied property required to have a value (that is, to be dependency-injected)?
191         * <p>This implementation looks for the existence of a
192         * {@link #setRequiredAnnotationType "required" annotation}
193         * on the supplied {@link PropertyDescriptor property}.
194         * @param propertyDescriptor the target PropertyDescriptor (never {@code null})
195         * @return {@code true} if the supplied property has been marked as being required;
196         * {@code false} if not, or if the supplied property does not have a setter method
197         */
198        protected boolean isRequiredProperty(PropertyDescriptor propertyDescriptor) {
199                Method setter = propertyDescriptor.getWriteMethod();
200                return (setter != null && AnnotationUtils.getAnnotation(setter, getRequiredAnnotationType()) != null);
201        }
202
203        /**
204         * Build an exception message for the given list of invalid properties.
205         * @param invalidProperties the list of names of invalid properties
206         * @param beanName the name of the bean
207         * @return the exception message
208         */
209        private String buildExceptionMessage(List<String> invalidProperties, String beanName) {
210                int size = invalidProperties.size();
211                StringBuilder sb = new StringBuilder();
212                sb.append(size == 1 ? "Property" : "Properties");
213                for (int i = 0; i < size; i++) {
214                        String propertyName = invalidProperties.get(i);
215                        if (i > 0) {
216                                if (i == (size - 1)) {
217                                        sb.append(" and");
218                                }
219                                else {
220                                        sb.append(",");
221                                }
222                        }
223                        sb.append(" '").append(propertyName).append("'");
224                }
225                sb.append(size == 1 ? " is" : " are");
226                sb.append(" required for bean '").append(beanName).append("'");
227                return sb.toString();
228        }
229
230}