1 16 17 package org.springframework.beans.factory.annotation; 18 19 import java.beans.PropertyDescriptor ; 20 import java.lang.annotation.Annotation ; 21 import java.lang.reflect.Method ; 22 import java.util.ArrayList ; 23 import java.util.List ; 24 25 import org.springframework.beans.BeansException; 26 import org.springframework.beans.PropertyValues; 27 import org.springframework.beans.factory.BeanInitializationException; 28 import org.springframework.beans.factory.config.BeanFactoryPostProcessor; 29 import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; 30 import org.springframework.core.annotation.AnnotationUtils; 31 import org.springframework.util.Assert; 32 33 57 public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { 58 59 private Class <? extends Annotation > requiredAnnotationType = Required.class; 60 61 62 70 public void setRequiredAnnotationType(Class <? extends Annotation > requiredAnnotationType) { 71 Assert.notNull(requiredAnnotationType, "'requiredAnnotationType' must not be null"); 72 this.requiredAnnotationType = requiredAnnotationType; 73 } 74 75 78 protected Class <? extends Annotation > getRequiredAnnotationType() { 79 return this.requiredAnnotationType; 80 } 81 82 83 public PropertyValues postProcessPropertyValues( 84 PropertyValues pvs, PropertyDescriptor [] pds, Object bean, String beanName) 85 throws BeansException { 86 87 List <String > invalidProperties = new ArrayList <String >(); 88 for (PropertyDescriptor pd : pds) { 89 if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) { 90 invalidProperties.add(pd.getName()); 91 } 92 } 93 if (!invalidProperties.isEmpty()) { 94 throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName)); 95 } 96 return pvs; 97 } 98 99 108 protected boolean isRequiredProperty(PropertyDescriptor propertyDescriptor) { 109 Method setter = propertyDescriptor.getWriteMethod(); 110 return (setter != null && AnnotationUtils.getAnnotation(setter, getRequiredAnnotationType()) != null); 111 } 112 113 119 private String buildExceptionMessage(List <String > invalidProperties, String beanName) { 120 int size = invalidProperties.size(); 121 StringBuilder sb = new StringBuilder (); 122 sb.append(size == 1 ? "Property" : "Properties"); 123 for (int i = 0; i < size; i++) { 124 String propertyName = invalidProperties.get(i); 125 if (i > 0) { 126 if (i == (size - 1)) { 127 sb.append(" and"); 128 } 129 else { 130 sb.append(","); 131 } 132 } 133 sb.append(" '").append(propertyName).append("'"); 134 } 135 sb.append(size == 1 ? " is" : " are"); 136 sb.append(" required for bean '").append(beanName).append("'"); 137 return sb.toString(); 138 } 139 140 } 141 | Popular Tags |