001: /*
002: * Copyright 2002-2007 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: * http://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:
017: package org.springframework.beans.factory.annotation;
018:
019: import java.beans.PropertyDescriptor;
020: import java.lang.annotation.Annotation;
021: import java.lang.reflect.Method;
022: import java.util.ArrayList;
023: import java.util.Collections;
024: import java.util.HashSet;
025: import java.util.List;
026: import java.util.Set;
027:
028: import org.springframework.beans.BeansException;
029: import org.springframework.beans.PropertyValues;
030: import org.springframework.beans.factory.BeanInitializationException;
031: import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
032: import org.springframework.core.annotation.AnnotationUtils;
033: import org.springframework.util.Assert;
034:
035: /**
036: * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
037: * that enforces required JavaBean properties to have been configured.
038: * Required bean properties are detected through a Java 5 annotation:
039: * by default, Spring's {@link Required} annotation.
040: *
041: * <p>The motivation for the existence of this BeanPostProcessor is to allow
042: * developers to annotate the setter properties of their own classes with an
043: * arbitrary JDK 1.5 annotation to indicate that the container must check
044: * for the configuration of a dependency injected value. This neatly pushes
045: * responsibility for such checking onto the container (where it arguably belongs),
046: * and obviates the need (<b>in part</b>) for a developer to code a method that
047: * simply checks that all required properties have actually been set.
048: *
049: * <p>Please note that an 'init' method may still need to implemented (and may
050: * still be desirable), because all that this class does is enforce that a
051: * 'required' property has actually been configured with a value. It does
052: * <b>not</b> check anything else... In particular, it does not check that a
053: * configured value is not <code>null</code>.
054: *
055: * <p>Note: A default RequiredAnnotationBeanPostProcessor will be registered
056: * by the "context:annotation-config" and "context:component-scan" XML tags.
057: * Remove or turn off the default annotation configuration there if you intend
058: * to specify a custom RequiredAnnotationBeanPostProcessor bean definition.
059: *
060: * @author Rob Harrop
061: * @author Juergen Hoeller
062: * @since 2.0
063: * @see #setRequiredAnnotationType
064: * @see Required
065: */
066: public class RequiredAnnotationBeanPostProcessor extends
067: InstantiationAwareBeanPostProcessorAdapter {
068:
069: private Class<? extends Annotation> requiredAnnotationType = Required.class;
070:
071: /** Cache for validated bean names, skipping re-validation for the same bean */
072: private final Set<String> validatedBeanNames = Collections
073: .synchronizedSet(new HashSet<String>());
074:
075: /**
076: * Set the 'required' annotation type, to be used on bean property
077: * setter methods.
078: * <p>The default required annotation type is the Spring-provided
079: * {@link Required} annotation.
080: * <p>This setter property exists so that developers can provide their own
081: * (non-Spring-specific) annotation type to indicate that a property value
082: * is required.
083: */
084: public void setRequiredAnnotationType(
085: Class<? extends Annotation> requiredAnnotationType) {
086: Assert.notNull(requiredAnnotationType,
087: "'requiredAnnotationType' must not be null");
088: this .requiredAnnotationType = requiredAnnotationType;
089: }
090:
091: /**
092: * Return the 'required' annotation type.
093: */
094: protected Class<? extends Annotation> getRequiredAnnotationType() {
095: return this .requiredAnnotationType;
096: }
097:
098: public PropertyValues postProcessPropertyValues(PropertyValues pvs,
099: PropertyDescriptor[] pds, Object bean, String beanName)
100: throws BeansException {
101:
102: if (!this .validatedBeanNames.contains(beanName)) {
103: List<String> invalidProperties = new ArrayList<String>();
104: for (PropertyDescriptor pd : pds) {
105: if (isRequiredProperty(pd)
106: && !pvs.contains(pd.getName())) {
107: invalidProperties.add(pd.getName());
108: }
109: }
110: if (!invalidProperties.isEmpty()) {
111: throw new BeanInitializationException(
112: buildExceptionMessage(invalidProperties,
113: beanName));
114: }
115: this .validatedBeanNames.add(beanName);
116: }
117: return pvs;
118: }
119:
120: /**
121: * Is the supplied property required to have a value (that is, to be dependency-injected)?
122: * <p>This implementation looks for the existence of a
123: * {@link #setRequiredAnnotationType "required" annotation}
124: * on the supplied {@link PropertyDescriptor property}.
125: * @param propertyDescriptor the target PropertyDescriptor (never <code>null</code>)
126: * @return <code>true</code> if the supplied property has been marked as being required;
127: * <code>false</code> if not, or if the supplied property does not have a setter method
128: */
129: protected boolean isRequiredProperty(
130: PropertyDescriptor propertyDescriptor) {
131: Method setter = propertyDescriptor.getWriteMethod();
132: return (setter != null && AnnotationUtils.getAnnotation(setter,
133: getRequiredAnnotationType()) != null);
134: }
135:
136: /**
137: * Build an exception message for the given list of invalid properties.
138: * @param invalidProperties the list of names of invalid properties
139: * @param beanName the name of the bean
140: * @return the exception message
141: */
142: private String buildExceptionMessage(
143: List<String> invalidProperties, String beanName) {
144: int size = invalidProperties.size();
145: StringBuilder sb = new StringBuilder();
146: sb.append(size == 1 ? "Property" : "Properties");
147: for (int i = 0; i < size; i++) {
148: String propertyName = invalidProperties.get(i);
149: if (i > 0) {
150: if (i == (size - 1)) {
151: sb.append(" and");
152: } else {
153: sb.append(",");
154: }
155: }
156: sb.append(" '").append(propertyName).append("'");
157: }
158: sb.append(size == 1 ? " is" : " are");
159: sb.append(" required for bean '").append(beanName).append("'");
160: return sb.toString();
161: }
162:
163: }
|