EL container integration; support for contextual objects; removal of deprecated Spring 2.0 functionality; Java 5 code style

This commit is contained in:
Juergen Hoeller
2008-11-20 02:10:53 +00:00
parent 369821dd66
commit 347f34c68a
281 changed files with 6120 additions and 9903 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.beans;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -66,11 +65,10 @@ public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySup
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
throws BeansException {
List propertyAccessExceptions = null;
List propertyValues = (pvs instanceof MutablePropertyValues ?
List<PropertyAccessException> propertyAccessExceptions = null;
List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
for (Iterator it = propertyValues.iterator(); it.hasNext();) {
PropertyValue pv = (PropertyValue) it.next();
for (PropertyValue pv : propertyValues) {
try {
// This method may throw any BeansException, which won't be caught
// here, if there is a critical failure such as no matching field.
@@ -91,7 +89,7 @@ public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySup
}
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new LinkedList();
propertyAccessExceptions = new LinkedList<PropertyAccessException>();
}
propertyAccessExceptions.add(ex);
}
@@ -99,7 +97,7 @@ public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySup
// If we encountered individual exceptions, throw the composite exception.
if (propertyAccessExceptions != null) {
PropertyAccessException[] paeArray = (PropertyAccessException[])
PropertyAccessException[] paeArray =
propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]);
throw new PropertyBatchUpdateException(paeArray);
}

View File

@@ -56,7 +56,8 @@ public abstract class BeanUtils {
private static final Log logger = LogFactory.getLog(BeanUtils.class);
private static final Map unknownEditorTypes = Collections.synchronizedMap(new WeakHashMap());
private static final Map<Class, Boolean> unknownEditorTypes =
Collections.synchronizedMap(new WeakHashMap<Class, Boolean>());
/**
@@ -75,7 +76,7 @@ public abstract class BeanUtils {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
return instantiateClass(clazz.getDeclaredConstructor((Class[]) null), null);
return instantiateClass(clazz.getDeclaredConstructor());
}
catch (NoSuchMethodException ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
@@ -93,7 +94,7 @@ public abstract class BeanUtils {
* @return the new instance
* @throws BeanInstantiationException if the bean cannot be instantiated
*/
public static Object instantiateClass(Constructor ctor, Object[] args) throws BeanInstantiationException {
public static Object instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor);
@@ -224,12 +225,11 @@ public abstract class BeanUtils {
Method targetMethod = null;
int numMethodsFoundWithCurrentMinimumArgs = 0;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(methodName)) {
int numParams = methods[i].getParameterTypes().length;
if (targetMethod == null ||
numParams < targetMethod.getParameterTypes().length) {
targetMethod = methods[i];
for (Method method : methods) {
if (method.getName().equals(methodName)) {
int numParams = method.getParameterTypes().length;
if (targetMethod == null || numParams < targetMethod.getParameterTypes().length) {
targetMethod = method;
numMethodsFoundWithCurrentMinimumArgs = 1;
}
else {
@@ -341,8 +341,7 @@ public abstract class BeanUtils {
public static PropertyDescriptor findPropertyForMethod(Method method) throws BeansException {
Assert.notNull(method, "Method must not be null");
PropertyDescriptor[] pds = getPropertyDescriptors(method.getDeclaringClass());
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
for (PropertyDescriptor pd : pds) {
if (method.equals(pd.getReadMethod()) || method.equals(pd.getWriteMethod())) {
return pd;
}
@@ -360,7 +359,7 @@ public abstract class BeanUtils {
* @return the corresponding editor, or <code>null</code> if none found
*/
public static PropertyEditor findEditorByConvention(Class targetType) {
if (targetType == null || unknownEditorTypes.containsKey(targetType)) {
if (targetType == null || targetType.isArray() || unknownEditorTypes.containsKey(targetType)) {
return null;
}
ClassLoader cl = targetType.getClassLoader();
@@ -400,8 +399,8 @@ public abstract class BeanUtils {
*/
public static Class findPropertyType(String propertyName, Class[] beanClasses) {
if (beanClasses != null) {
for (int i = 0; i < beanClasses.length; i++) {
PropertyDescriptor pd = getPropertyDescriptor(beanClasses[i], propertyName);
for (Class beanClass : beanClasses) {
PropertyDescriptor pd = getPropertyDescriptor(beanClass, propertyName);
if (pd != null) {
return pd.getPropertyType();
}
@@ -455,36 +454,6 @@ public abstract class BeanUtils {
clazz.equals(Locale.class) || clazz.equals(Class.class);
}
/**
* Determine if the given target type is assignable from the given value
* type, assuming setting by reflection. Considers primitive wrapper
* classes as assignable to the corresponding primitive types.
* @param targetType the target type
* @param valueType the value type that should be assigned to the target type
* @return if the target type is assignable from the value type
* @deprecated as of Spring 2.0, in favor of <code>ClassUtils.isAssignable</code>
* @see org.springframework.util.ClassUtils#isAssignable(Class, Class)
*/
@Deprecated
public static boolean isAssignable(Class targetType, Class valueType) {
return ClassUtils.isAssignable(targetType, valueType);
}
/**
* Determine if the given type is assignable from the given value,
* assuming setting by reflection. Considers primitive wrapper classes
* as assignable to the corresponding primitive types.
* @param type the target type
* @param value the value that should be assigned to the type
* @return if the type is assignable from the value
* @deprecated as of Spring 2.0, in favor of <code>ClassUtils.isAssignableValue</code>
* @see org.springframework.util.ClassUtils#isAssignableValue(Class, Object)
*/
@Deprecated
public static boolean isAssignable(Class type, Object value) {
return ClassUtils.isAssignableValue(type, value);
}
/**
* Copy the property values of the given source bean into the target bean.
@@ -571,8 +540,7 @@ public abstract class BeanUtils {
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
for (int i = 0; i < targetPds.length; i++) {
PropertyDescriptor targetPd = targetPds[i];
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null &&
(ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
@@ -582,12 +550,12 @@ public abstract class BeanUtils {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source, new Object[0]);
Object value = readMethod.invoke(source);
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, new Object[] {value});
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException("Could not copy properties from source to target", ex);

View File

@@ -52,15 +52,6 @@ import java.beans.PropertyDescriptor;
*/
public interface BeanWrapper extends ConfigurablePropertyAccessor {
/**
* Change the wrapped JavaBean object.
* @param obj the bean instance to wrap
* @deprecated as of Spring 2.5,
* in favor of recreating a BeanWrapper per target instance
*/
@Deprecated
void setWrappedInstance(Object obj);
/**
* Return the bean instance wrapped by this object, if any.
* @return the bean instance, or <code>null</code> if none set

View File

@@ -33,7 +33,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.JdkVersion;
import org.springframework.core.MethodParameter;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
@@ -349,15 +348,6 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
return false;
}
/**
* @deprecated in favor of <code>convertIfNecessary</code>
* @see #convertIfNecessary(Object, Class)
*/
@Deprecated
public Object doTypeConversionIfNecessary(Object value, Class requiredType) throws TypeMismatchException {
return convertIfNecessary(value, requiredType, null);
}
public Object convertIfNecessary(
Object value, Class requiredType, MethodParameter methodParam) throws TypeMismatchException {
try {
@@ -584,10 +574,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
}
else if (value instanceof Map) {
Map map = (Map) value;
Class mapKeyType = null;
if (JdkVersion.isAtLeastJava15()) {
mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1);
}
Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1);
// IMPORTANT: Do not pass full property name in here - property editors
// must not kick in for map keys but rather only for map values.
Object convertedMapKey = this.typeConverterDelegate.convertIfNecessary(key, mapKeyType);
@@ -711,11 +698,8 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
}
else if (propValue instanceof List) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class requiredType = null;
if (JdkVersion.isAtLeastJava15()) {
requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
pd.getReadMethod(), tokens.keys.length);
}
Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
pd.getReadMethod(), tokens.keys.length);
List list = (List) propValue;
int index = Integer.parseInt(key);
Object oldValue = null;
@@ -751,14 +735,10 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
}
else if (propValue instanceof Map) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class mapKeyType = null;
Class mapValueType = null;
if (JdkVersion.isAtLeastJava15()) {
mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
pd.getReadMethod(), tokens.keys.length);
mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
pd.getReadMethod(), tokens.keys.length);
}
Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
pd.getReadMethod(), tokens.keys.length);
Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
pd.getReadMethod(), tokens.keys.length);
Map map = (Map) propValue;
Object convertedMapKey = null;
Object convertedMapValue = null;
@@ -870,7 +850,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
StringBuilder sb = new StringBuilder(getClass().getName());
if (this.object != null) {
sb.append(": wrapping object [").append(ObjectUtils.identityToString(this.object)).append("]");
}

View File

@@ -33,7 +33,6 @@ import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.JdkVersion;
import org.springframework.util.ClassUtils;
/**
@@ -64,14 +63,14 @@ public class CachedIntrospectionResults {
* Set of ClassLoaders that this CachedIntrospectionResults class will always
* accept classes from, even if the classes do not qualify as cache-safe.
*/
static final Set acceptedClassLoaders = Collections.synchronizedSet(new HashSet());
static final Set<ClassLoader> acceptedClassLoaders = Collections.synchronizedSet(new HashSet<ClassLoader>());
/**
* Map keyed by class containing CachedIntrospectionResults.
* Needs to be a WeakHashMap with WeakReferences as values to allow
* for proper garbage collection in case of multiple class loaders.
*/
static final Map classCache = Collections.synchronizedMap(new WeakHashMap());
static final Map<Class, Object> classCache = Collections.synchronizedMap(new WeakHashMap<Class, Object>());
/**
@@ -150,7 +149,7 @@ public class CachedIntrospectionResults {
if (logger.isDebugEnabled()) {
logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
}
classCache.put(beanClass, new WeakReference(results));
classCache.put(beanClass, new WeakReference<CachedIntrospectionResults>(results));
}
}
return results;
@@ -166,9 +165,9 @@ public class CachedIntrospectionResults {
private static boolean isClassLoaderAccepted(ClassLoader classLoader) {
// Iterate over array copy in order to avoid synchronization for the entire
// ClassLoader check (avoiding a synchronized acceptedClassLoaders Iterator).
Object[] acceptedLoaderArray = acceptedClassLoaders.toArray();
for (int i = 0; i < acceptedLoaderArray.length; i++) {
ClassLoader registeredLoader = (ClassLoader) acceptedLoaderArray[i];
ClassLoader[] acceptedLoaderArray =
acceptedClassLoaders.toArray(new ClassLoader[acceptedClassLoaders.size()]);
for (ClassLoader registeredLoader : acceptedLoaderArray) {
if (isUnderneathClassLoader(classLoader, registeredLoader)) {
return true;
}
@@ -204,7 +203,7 @@ public class CachedIntrospectionResults {
private final BeanInfo beanInfo;
/** PropertyDescriptor objects keyed by property name String */
private final Map propertyDescriptorCache;
private final Map<String, PropertyDescriptor> propertyDescriptorCache;
/**
@@ -233,23 +232,19 @@ public class CachedIntrospectionResults {
if (logger.isTraceEnabled()) {
logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
}
this.propertyDescriptorCache = new HashMap();
this.propertyDescriptorCache = new HashMap<String, PropertyDescriptor>();
// This call is slow so we do it once.
PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
for (PropertyDescriptor pd : pds) {
if (logger.isTraceEnabled()) {
logger.trace("Found bean property '" + pd.getName() + "'" +
(pd.getPropertyType() != null ?
" of type [" + pd.getPropertyType().getName() + "]" : "") +
(pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") +
(pd.getPropertyEditorClass() != null ?
"; editor [" + pd.getPropertyEditorClass().getName() + "]" : ""));
}
if (JdkVersion.isAtLeastJava15()) {
pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(),
pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass());
"; editor [" + pd.getPropertyEditorClass().getName() + "]" : ""));
}
pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
pd.getWriteMethod(), pd.getPropertyEditorClass());
this.propertyDescriptorCache.put(pd.getName(), pd);
}
}
@@ -267,7 +262,7 @@ public class CachedIntrospectionResults {
}
PropertyDescriptor getPropertyDescriptor(String propertyName) {
return (PropertyDescriptor) this.propertyDescriptorCache.get(propertyName);
return this.propertyDescriptorCache.get(propertyName);
}
}

View File

@@ -19,7 +19,6 @@ package org.springframework.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -39,9 +38,9 @@ import org.springframework.util.StringUtils;
public class MutablePropertyValues implements PropertyValues, Serializable {
/** List of PropertyValue objects */
private final List propertyValueList;
private final List<PropertyValue> propertyValueList;
private Set processedProperties;
private Set<String> processedProperties;
private volatile boolean converted = false;
@@ -53,7 +52,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
* @see #addPropertyValue(String, Object)
*/
public MutablePropertyValues() {
this.propertyValueList = new ArrayList();
this.propertyValueList = new ArrayList<PropertyValue>();
}
/**
@@ -68,14 +67,13 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
// There is no replacement of existing property values.
if (original != null) {
PropertyValue[] pvs = original.getPropertyValues();
this.propertyValueList = new ArrayList(pvs.length);
for (int i = 0; i < pvs.length; i++) {
PropertyValue newPv = new PropertyValue(pvs[i]);
this.propertyValueList.add(newPv);
this.propertyValueList = new ArrayList<PropertyValue>(pvs.length);
for (PropertyValue pv : pvs) {
this.propertyValueList.add(new PropertyValue(pv));
}
}
else {
this.propertyValueList = new ArrayList(0);
this.propertyValueList = new ArrayList<PropertyValue>(0);
}
}
@@ -84,20 +82,17 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
* @param original Map with property values keyed by property name Strings
* @see #addPropertyValues(Map)
*/
public MutablePropertyValues(Map original) {
public MutablePropertyValues(Map<?, ?> original) {
// We can optimize this because it's all new:
// There is no replacement of existing property values.
if (original != null) {
this.propertyValueList = new ArrayList(original.size());
Iterator it = original.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
PropertyValue newPv = new PropertyValue((String) entry.getKey(), entry.getValue());
this.propertyValueList.add(newPv);
this.propertyValueList = new ArrayList<PropertyValue>(original.size());
for (Map.Entry entry : original.entrySet()) {
this.propertyValueList.add(new PropertyValue(entry.getKey().toString(), entry.getValue()));
}
}
else {
this.propertyValueList = new ArrayList(0);
this.propertyValueList = new ArrayList<PropertyValue>(0);
}
}
@@ -108,8 +103,9 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
* It is not intended for typical programmatic use.
* @param propertyValueList List of PropertyValue objects
*/
public MutablePropertyValues(List propertyValueList) {
this.propertyValueList = (propertyValueList != null ? propertyValueList : new ArrayList());
public MutablePropertyValues(List<PropertyValue> propertyValueList) {
this.propertyValueList =
(propertyValueList != null ? propertyValueList : new ArrayList<PropertyValue>());
}
@@ -119,7 +115,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
* <p>This is an accessor for optimized access to all PropertyValue objects.
* It is not intended for typical programmatic use.
*/
public List getPropertyValueList() {
public List<PropertyValue> getPropertyValueList() {
return this.propertyValueList;
}
@@ -134,9 +130,8 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
public MutablePropertyValues addPropertyValues(PropertyValues other) {
if (other != null) {
PropertyValue[] pvs = other.getPropertyValues();
for (int i = 0; i < pvs.length; i++) {
PropertyValue newPv = new PropertyValue(pvs[i]);
addPropertyValue(newPv);
for (PropertyValue pv : pvs) {
addPropertyValue(new PropertyValue(pv));
}
}
return this;
@@ -149,13 +144,10 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
* @return this object to allow creating objects, adding multiple
* PropertyValues in a single statement
*/
public MutablePropertyValues addPropertyValues(Map other) {
public MutablePropertyValues addPropertyValues(Map<?, ?> other) {
if (other != null) {
Iterator it = other.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
PropertyValue newPv = new PropertyValue((String) entry.getKey(), entry.getValue());
addPropertyValue(newPv);
for (Map.Entry<?, ?> entry : other.entrySet()) {
addPropertyValue(new PropertyValue(entry.getKey().toString(), entry.getValue()));
}
}
return this;
@@ -170,7 +162,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
*/
public MutablePropertyValues addPropertyValue(PropertyValue pv) {
for (int i = 0; i < this.propertyValueList.size(); i++) {
PropertyValue currentPv = (PropertyValue) this.propertyValueList.get(i);
PropertyValue currentPv = this.propertyValueList.get(i);
if (currentPv.getName().equals(pv.getName())) {
pv = mergeIfRequired(pv, currentPv);
setPropertyValueAt(pv, i);
@@ -243,13 +235,11 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
public PropertyValue[] getPropertyValues() {
return (PropertyValue[])
this.propertyValueList.toArray(new PropertyValue[this.propertyValueList.size()]);
return this.propertyValueList.toArray(new PropertyValue[this.propertyValueList.size()]);
}
public PropertyValue getPropertyValue(String propertyName) {
for (int i = 0; i < this.propertyValueList.size(); i++) {
PropertyValue pv = (PropertyValue) this.propertyValueList.get(i);
for (PropertyValue pv : this.propertyValueList) {
if (pv.getName().equals(propertyName)) {
return pv;
}
@@ -267,7 +257,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
*/
public void registerProcessedProperty(String propertyName) {
if (this.processedProperties == null) {
this.processedProperties = new HashSet();
this.processedProperties = new HashSet<String>();
}
this.processedProperties.add(propertyName);
}
@@ -292,8 +282,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
}
// for each property value in the new set
for (Iterator it = this.propertyValueList.iterator(); it.hasNext();) {
PropertyValue newPv = (PropertyValue) it.next();
for (PropertyValue newPv : this.propertyValueList) {
// if there wasn't an old one, add it
PropertyValue pvOld = old.getPropertyValue(newPv.getName());
if (pvOld == null) {
@@ -345,7 +334,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
@Override
public String toString() {
PropertyValue[] pvs = getPropertyValues();
StringBuffer sb = new StringBuffer("PropertyValues: length=" + pvs.length + "; ");
StringBuilder sb = new StringBuilder("PropertyValues: length=" + pvs.length + "; ");
sb.append(StringUtils.arrayToDelimitedString(pvs, "; "));
return sb.toString();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -141,26 +141,26 @@ public abstract class PropertyAccessorUtils {
return "";
}
StringBuffer buf = new StringBuffer(propertyName);
StringBuilder sb = new StringBuilder(propertyName);
int searchIndex = 0;
while (searchIndex != -1) {
int keyStart = buf.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX, searchIndex);
int keyStart = sb.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX, searchIndex);
searchIndex = -1;
if (keyStart != -1) {
int keyEnd = buf.indexOf(
int keyEnd = sb.indexOf(
PropertyAccessor.PROPERTY_KEY_SUFFIX, keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length());
if (keyEnd != -1) {
String key = buf.substring(keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length(), keyEnd);
String key = sb.substring(keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length(), keyEnd);
if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) {
buf.delete(keyStart + 1, keyStart + 2);
buf.delete(keyEnd - 2, keyEnd - 1);
sb.delete(keyStart + 1, keyStart + 2);
sb.delete(keyEnd - 2, keyEnd - 1);
keyEnd = keyEnd - 2;
}
searchIndex = keyEnd + PropertyAccessor.PROPERTY_KEY_SUFFIX.length();
}
}
}
return buf.toString();
return sb.toString();
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -82,7 +82,7 @@ public class PropertyBatchUpdateException extends BeansException {
@Override
public String getMessage() {
StringBuffer sb = new StringBuffer("Failed properties: ");
StringBuilder sb = new StringBuilder("Failed properties: ");
for (int i = 0; i < this.propertyAccessExceptions.length; i++) {
sb.append(this.propertyAccessExceptions[i].getMessage());
if (i < this.propertyAccessExceptions.length - 1) {
@@ -94,7 +94,7 @@ public class PropertyBatchUpdateException extends BeansException {
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName()).append("; nested PropertyAccessExceptions (");
sb.append(getExceptionCount()).append(") are:");
for (int i = 0; i < this.propertyAccessExceptions.length; i++) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -94,29 +94,29 @@ final class PropertyMatches {
* indicating the possible property matches.
*/
public String buildErrorMessage() {
StringBuffer buf = new StringBuffer();
buf.append("Bean property '");
buf.append(this.propertyName);
buf.append("' is not writable or has an invalid setter method. ");
StringBuilder msg = new StringBuilder();
msg.append("Bean property '");
msg.append(this.propertyName);
msg.append("' is not writable or has an invalid setter method. ");
if (ObjectUtils.isEmpty(this.possibleMatches)) {
buf.append("Does the parameter type of the setter match the return type of the getter?");
msg.append("Does the parameter type of the setter match the return type of the getter?");
}
else {
buf.append("Did you mean ");
msg.append("Did you mean ");
for (int i = 0; i < this.possibleMatches.length; i++) {
buf.append('\'');
buf.append(this.possibleMatches[i]);
msg.append('\'');
msg.append(this.possibleMatches[i]);
if (i < this.possibleMatches.length - 2) {
buf.append("', ");
msg.append("', ");
}
else if (i == this.possibleMatches.length - 2){
buf.append("', or ");
msg.append("', or ");
}
}
buf.append("'?");
msg.append("'?");
}
return buf.toString();
return msg.toString();
}

View File

@@ -18,21 +18,17 @@ package org.springframework.beans;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.CollectionFactory;
import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.JdkVersion;
import org.springframework.core.MethodParameter;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
@@ -53,8 +49,6 @@ class TypeConverterDelegate {
private static final Log logger = LogFactory.getLog(TypeConverterDelegate.class);
private static final Map unknownEditorTypes = Collections.synchronizedMap(new WeakHashMap());
private final PropertyEditorRegistrySupport propertyEditorRegistry;
private final Object targetObject;
@@ -195,7 +189,7 @@ class TypeConverterDelegate {
}
else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
String strValue = ((String) convertedValue).trim();
if (JdkVersion.isAtLeastJava15() && requiredType.isEnum() && "".equals(strValue)) {
if (requiredType.isEnum() && "".equals(strValue)) {
// It's an empty enum identifier: reset the enum value to null.
return null;
}
@@ -216,7 +210,7 @@ class TypeConverterDelegate {
if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
// Definitely doesn't match: throw IllegalArgumentException.
StringBuffer msg = new StringBuffer();
StringBuilder msg = new StringBuilder();
msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
if (propertyName != null) {
@@ -244,15 +238,7 @@ class TypeConverterDelegate {
protected PropertyEditor findDefaultEditor(Class requiredType, PropertyDescriptor descriptor) {
PropertyEditor editor = null;
if (descriptor != null) {
if (JdkVersion.isAtLeastJava15()) {
editor = descriptor.createPropertyEditor(this.targetObject);
}
else {
Class editorClass = descriptor.getPropertyEditorClass();
if (editorClass != null) {
editor = (PropertyEditor) BeanUtils.instantiateClass(editorClass);
}
}
editor = descriptor.createPropertyEditor(this.targetObject);
}
if (editor == null && requiredType != null) {
// No custom editor -> check BeanWrapperImpl's default editors.
@@ -260,19 +246,6 @@ class TypeConverterDelegate {
if (editor == null && !String.class.equals(requiredType)) {
// No BeanWrapper default editor -> check standard JavaBean editor.
editor = BeanUtils.findEditorByConvention(requiredType);
if (editor == null && !unknownEditorTypes.containsKey(requiredType)) {
// Deprecated global PropertyEditorManager fallback...
editor = PropertyEditorManager.findEditor(requiredType);
if (editor == null) {
// Regular case as of Spring 2.5
unknownEditorTypes.put(requiredType, Boolean.TRUE);
}
else {
logger.warn("PropertyEditor [" + editor.getClass().getName() +
"] found through deprecated global PropertyEditorManager fallback - " +
"consider using a more isolated form of registration, e.g. on the BeanWrapper/BeanFactory!");
}
}
}
}
return editor;
@@ -425,7 +398,7 @@ class TypeConverterDelegate {
Collection original, String propertyName, MethodParameter methodParam) {
Class elementType = null;
if (methodParam != null && JdkVersion.isAtLeastJava15()) {
if (methodParam != null) {
elementType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam);
}
if (elementType == null &&
@@ -475,7 +448,7 @@ class TypeConverterDelegate {
protected Map convertToTypedMap(Map original, String propertyName, MethodParameter methodParam) {
Class keyType = null;
Class valueType = null;
if (methodParam != null && JdkVersion.isAtLeastJava15()) {
if (methodParam != null) {
keyType = GenericCollectionTypeResolver.getMapKeyParameterType(methodParam);
valueType = GenericCollectionTypeResolver.getMapValueParameterType(methodParam);
}

View File

@@ -18,7 +18,6 @@ package org.springframework.beans.factory;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@@ -37,7 +36,7 @@ public class BeanCreationException extends FatalBeanException {
private String resourceDescription;
private List relatedCauses;
private List<Throwable> relatedCauses;
/**
@@ -129,7 +128,7 @@ public class BeanCreationException extends FatalBeanException {
*/
public void addRelatedCause(Throwable ex) {
if (this.relatedCauses == null) {
this.relatedCauses = new LinkedList();
this.relatedCauses = new LinkedList<Throwable>();
}
this.relatedCauses.add(ex);
}
@@ -142,16 +141,15 @@ public class BeanCreationException extends FatalBeanException {
if (this.relatedCauses == null) {
return null;
}
return (Throwable[]) this.relatedCauses.toArray(new Throwable[this.relatedCauses.size()]);
return this.relatedCauses.toArray(new Throwable[this.relatedCauses.size()]);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(super.toString());
StringBuilder sb = new StringBuilder(super.toString());
if (this.relatedCauses != null) {
for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) {
Throwable relatedCause = (Throwable) it.next();
for (Throwable relatedCause : this.relatedCauses) {
sb.append("\nRelated cause: ");
sb.append(relatedCause);
}
@@ -164,8 +162,7 @@ public class BeanCreationException extends FatalBeanException {
synchronized (ps) {
super.printStackTrace(ps);
if (this.relatedCauses != null) {
for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) {
Throwable relatedCause = (Throwable) it.next();
for (Throwable relatedCause : this.relatedCauses) {
ps.println("Related cause:");
relatedCause.printStackTrace(ps);
}
@@ -178,8 +175,7 @@ public class BeanCreationException extends FatalBeanException {
synchronized (pw) {
super.printStackTrace(pw);
if (this.relatedCauses != null) {
for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) {
Throwable relatedCause = (Throwable) it.next();
for (Throwable relatedCause : this.relatedCauses) {
pw.println("Related cause:");
relatedCause.printStackTrace(pw);
}
@@ -193,8 +189,7 @@ public class BeanCreationException extends FatalBeanException {
return true;
}
if (this.relatedCauses != null) {
for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) {
Throwable relatedCause = (Throwable) it.next();
for (Throwable relatedCause : this.relatedCauses) {
if (relatedCause instanceof NestedRuntimeException &&
((NestedRuntimeException) relatedCause).contains(exClass)) {
return true;

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.FatalBeanException;
/**
* Exception that indicates an expression evaluation attempt having failed.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class BeanExpressionException extends FatalBeanException {
/**
* Create a new BeanExpressionException with the specified message.
* @param msg the detail message
*/
public BeanExpressionException(String msg) {
super(msg);
}
/**
* Create a new BeanExpressionException with the specified message
* and root cause.
* @param msg the detail message
* @param cause the root cause
*/
public BeanExpressionException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -147,7 +147,7 @@ public interface BeanFactory {
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
*/
Object getBean(String name, Class requiredType) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
/**
* Return an instance, which may be shared or independent, of the specified bean.

View File

@@ -18,7 +18,6 @@ package org.springframework.beans.factory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -146,10 +145,9 @@ public abstract class BeanFactoryUtils {
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
List resultList = new ArrayList();
List<String> resultList = new ArrayList<String>();
resultList.addAll(Arrays.asList(result));
for (int i = 0; i < parentResult.length; i++) {
String beanName = parentResult[i];
for (String beanName : parentResult) {
if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) {
resultList.add(beanName);
}
@@ -190,10 +188,9 @@ public abstract class BeanFactoryUtils {
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
List resultList = new ArrayList();
List<String> resultList = new ArrayList<String>();
resultList.addAll(Arrays.asList(result));
for (int i = 0; i < parentResult.length; i++) {
String beanName = parentResult[i];
for (String beanName : parentResult) {
if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) {
resultList.add(beanName);
}
@@ -216,20 +213,19 @@ public abstract class BeanFactoryUtils {
* @return the Map of matching bean instances, or an empty Map if none
* @throws BeansException if a bean could not be created
*/
public static Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type)
throws BeansException {
public static <T> Map<String, T> beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map result = new LinkedHashMap(4);
Map<String, T> result = new LinkedHashMap<String, T>(4);
result.putAll(lbf.getBeansOfType(type));
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
Map parentResult = beansOfTypeIncludingAncestors(
Map<String, T> parentResult = beansOfTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
for (Iterator it = parentResult.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String beanName = (String) entry.getKey();
for (Map.Entry<String, T> entry : parentResult.entrySet()) {
String beanName = entry.getKey();
if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
result.put(beanName, entry.getValue());
}
@@ -261,21 +257,20 @@ public abstract class BeanFactoryUtils {
* @return the Map of matching bean instances, or an empty Map if none
* @throws BeansException if a bean could not be created
*/
public static Map beansOfTypeIncludingAncestors(
ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
public static <T> Map<String, T> beansOfTypeIncludingAncestors(
ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map result = new LinkedHashMap(4);
Map<String, T> result = new LinkedHashMap<String, T>(4);
result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit));
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
Map parentResult = beansOfTypeIncludingAncestors(
Map<String, T> parentResult = beansOfTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
for (Iterator it = parentResult.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String beanName = (String) entry.getKey();
for (Map.Entry<String, T> entry : parentResult.entrySet()) {
String beanName = entry.getKey();
if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
result.put(beanName, entry.getValue());
}

View File

@@ -50,7 +50,7 @@ package org.springframework.beans.factory;
* @see org.springframework.aop.framework.ProxyFactoryBean
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public interface FactoryBean {
public interface FactoryBean<T> {
/**
* Return an instance (possibly shared or independent) of the object
@@ -69,7 +69,7 @@ public interface FactoryBean {
* @throws Exception in case of creation errors
* @see FactoryBeanNotInitializedException
*/
Object getObject() throws Exception;
T getObject() throws Exception;
/**
* Return the type of object that this FactoryBean creates,
@@ -90,7 +90,7 @@ public interface FactoryBean {
* or <code>null</code> if not known at the time of the call
* @see ListableBeanFactory#getBeansOfType
*/
Class getObjectType();
Class<? extends T> getObjectType();
/**
* Is the object managed by this factory a singleton? That is,

View File

@@ -172,7 +172,7 @@ $ * <p>Does not consider any hierarchy this factory may participate in.
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
*/
Map getBeansOfType(Class type) throws BeansException;
<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;
/**
* Return the bean instances that match the given object type (including
@@ -207,7 +207,7 @@ $ * <p>Does not consider any hierarchy this factory may participate in.
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
*/
Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit)
<T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,7 +35,7 @@ import org.springframework.beans.BeansException;
* @since 1.0.2
* @see FactoryBean
*/
public interface ObjectFactory {
public interface ObjectFactory<T> {
/**
* Return an instance (possibly shared or independent)
@@ -43,6 +43,6 @@ public interface ObjectFactory {
* @return an instance of the bean (should never be <code>null</code>)
* @throws BeansException in case of creation errors
*/
Object getObject() throws BeansException;
T getObject() throws BeansException;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,7 +38,7 @@ package org.springframework.beans.factory;
* @see #isPrototype()
* @see #isSingleton()
*/
public interface SmartFactoryBean extends FactoryBean {
public interface SmartFactoryBean<T> extends FactoryBean<T> {
/**
* Is the object managed by this factory a prototype? That is,

View File

@@ -105,6 +105,8 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
private boolean requiredParameterValue = true;
private Class<? extends Annotation> valueAnnotationType = Value.class;
private int order = Ordered.LOWEST_PRECEDENCE - 2;
private ConfigurableListableBeanFactory beanFactory;
@@ -193,22 +195,25 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
List<Constructor> candidates = new ArrayList<Constructor>(rawCandidates.length);
Constructor requiredConstructor = null;
Constructor defaultConstructor = null;
for (int i = 0; i < rawCandidates.length; i++) {
Constructor<?> candidate = rawCandidates[i];
for (Constructor<?> candidate : rawCandidates) {
Annotation annotation = candidate.getAnnotation(getAutowiredAnnotationType());
if (annotation != null) {
if (requiredConstructor != null) {
throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate +
". Found another constructor with 'required' Autowired annotation: " + requiredConstructor);
". Found another constructor with 'required' Autowired annotation: " +
requiredConstructor);
}
if (candidate.getParameterTypes().length == 0) {
throw new IllegalStateException("Autowired annotation requires at least one argument: " + candidate);
throw new IllegalStateException(
"Autowired annotation requires at least one argument: " + candidate);
}
boolean required = determineRequiredStatus(annotation);
if (required) {
if (!candidates.isEmpty()) {
throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates +
". Found another constructor with 'required' Autowired annotation: " + requiredConstructor);
throw new BeanCreationException(
"Invalid autowire-marked constructors: " + candidates +
". Found another constructor with 'required' Autowired annotation: " +
requiredConstructor);
}
requiredConstructor = candidate;
}
@@ -223,7 +228,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
if (requiredConstructor == null && defaultConstructor != null) {
candidates.add(defaultConstructor);
}
candidateConstructors = (Constructor[]) candidates.toArray(new Constructor[candidates.size()]);
candidateConstructors = candidates.toArray(new Constructor[candidates.size()]);
}
else {
candidateConstructors = new Constructor[0];
@@ -329,7 +334,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
* @return the target beans, or an empty Collection if no bean of this type is found
* @throws BeansException if bean retrieval failed
*/
protected Map findAutowireCandidates(Class type) throws BeansException {
protected <T> Map<String, T> findAutowireCandidates(Class<T> type) throws BeansException {
if (this.beanFactory == null) {
throw new IllegalStateException("No BeanFactory configured - " +
"override the getBeanOfType method or specify the 'beanFactory' property");
@@ -361,12 +366,12 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
*/
private void registerDependentBeans(String beanName, Set<String> autowiredBeanNames) {
if (beanName != null) {
for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) {
String autowiredBeanName = (String) it.next();
for (String autowiredBeanName : autowiredBeanNames) {
beanFactory.registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' to bean named '" + autowiredBeanName + "'");
logger.debug(
"Autowiring by type from bean name '" + beanName + "' to bean named '" + autowiredBeanName +
"'");
}
}
}
@@ -463,7 +468,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
// Explicit value provided as part of the bean definition.
this.skip = Boolean.TRUE;
}
if (this.skip != null && this.skip.booleanValue()) {
if (this.skip != null && this.skip) {
return;
}
Method method = (Method) this.member;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,8 @@ import java.lang.annotation.Target;
* @author Juergen Hoeller
* @since 2.5
*/
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Inherited
@Documented
public @interface Qualifier {

View File

@@ -109,7 +109,7 @@ public class QualifierAnnotationAutowireCandidateResolver implements AutowireCan
}
AbstractBeanDefinition bd = (AbstractBeanDefinition) bdHolder.getBeanDefinition();
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
Annotation[] annotations = (Annotation[]) descriptor.getAnnotations();
Annotation[] annotations = descriptor.getAnnotations();
for (Annotation annotation : annotations) {
Class<? extends Annotation> type = annotation.annotationType();
if (isQualifier(type)) {

View File

@@ -0,0 +1,18 @@
package org.springframework.beans.factory.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Juergen Hoeller
* @since 3.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface Value {
String value();
}

View File

@@ -77,8 +77,8 @@ public abstract class AbstractFactoryBean
/**
* Set if a singleton should be created, or a new object
* on each request else. Default is <code>true</code> (a singleton).
* Set if a singleton should be created, or a new object on each request
* otherwise. Default is <code>true</code> (a singleton).
*/
public void setSingleton(boolean singleton) {
this.singleton = singleton;

View File

@@ -312,6 +312,6 @@ public interface AutowireCapableBeanFactory extends BeanFactory {
* @throws BeansException in dependency resolution failed
*/
Object resolveDependency(DependencyDescriptor descriptor, String beanName,
Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException;
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -119,7 +119,7 @@ public class BeanDefinitionHolder implements BeanMetadataElement {
* @see #getAliases()
*/
public String getShortDescription() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
sb.append("Bean definition with name '").append(this.beanName).append("'");
if (this.aliases != null) {
sb.append(" and aliases [").append(StringUtils.arrayToCommaDelimitedString(this.aliases)).append("]");
@@ -134,7 +134,7 @@ public class BeanDefinitionHolder implements BeanMetadataElement {
* @see #getBeanDefinition()
*/
public String getLongDescription() {
StringBuffer sb = new StringBuffer(getShortDescription());
StringBuilder sb = new StringBuilder(getShortDescription());
sb.append(": ").append(this.beanDefinition);
return sb.toString();
}

View File

@@ -176,12 +176,19 @@ public class BeanDefinitionVisitor {
visitBeanDefinition(((BeanDefinitionHolder) value).getBeanDefinition());
}
else if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
String newBeanName = resolveStringValue(ref.getBeanName());
RuntimeBeanReference ref = (RuntimeBeanReference) value;
String newBeanName = resolveStringValue(ref.getBeanName());
if (!newBeanName.equals(ref.getBeanName())) {
return new RuntimeBeanReference(newBeanName);
}
}
else if (value instanceof RuntimeBeanNameReference) {
RuntimeBeanNameReference ref = (RuntimeBeanNameReference) value;
String newBeanName = resolveStringValue(ref.getBeanName());
if (!newBeanName.equals(ref.getBeanName())) {
return new RuntimeBeanNameReference(newBeanName);
}
}
else if (value instanceof List) {
visitList((List) value);
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import org.springframework.beans.factory.BeanFactory;
/**
* Context object for evaluating an expression within a bean definition.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class BeanExpressionContext {
private final BeanFactory beanFactory;
private final Scope scope;
public BeanExpressionContext(BeanFactory beanFactory, Scope scope) {
this.beanFactory = beanFactory;
this.scope = scope;
}
public final BeanFactory getBeanFactory() {
return this.beanFactory;
}
public final Scope getScope() {
return this.scope;
}
public boolean containsObject(String key) {
return (this.beanFactory.containsBean(key) ||
this.scope.resolveContextualObject(key) != null);
}
public Object getObject(String key) {
if (this.beanFactory.containsBean(key)) {
return this.beanFactory.getBean(key);
}
else {
return this.scope.resolveContextualObject(key);
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
/**
* Strategy interface for resolving a value through evaluating it
* as an expression, if applicable.
*
* <p>A raw {@link org.springframework.beans.factory.BeanFactory} does not
* contain a default implementation of this strategy. However,
* {@link org.springframework.context.ApplicationContext} implementations
* will provide expression support out of the box.
*
* @author Juergen Hoeller
* @since 3.0
*/
public interface BeanExpressionResolver {
/**
* Evaluate the given value as an expression, if applicable;
* return the value as-is otherwise.
* @param value the value to check
* @param evalContext the evaluation context
* @return the resolved value (potentially the given value as-is)
* @throws BeansException if evaluation failed
*/
Object evaluate(String value, BeanExpressionContext evalContext) throws BeansException;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2005 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.beans.factory.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
@@ -30,10 +31,10 @@ import org.springframework.beans.factory.InitializingBean;
* one Log instance per class name, e.g. for common log topics.
*
* @author Juergen Hoeller
* @see org.apache.commons.logging.Log
* @since 16.11.2003
* @see org.apache.commons.logging.Log
*/
public class CommonsLogFactoryBean implements FactoryBean, InitializingBean {
public class CommonsLogFactoryBean implements FactoryBean<Log>, InitializingBean {
private Log log;
@@ -50,15 +51,15 @@ public class CommonsLogFactoryBean implements FactoryBean, InitializingBean {
public void afterPropertiesSet() {
if (this.log == null) {
throw new IllegalArgumentException("logName is required");
throw new IllegalArgumentException("'logName' is required");
}
}
public Object getObject() {
return log;
public Log getObject() {
return this.log;
}
public Class getObjectType() {
public Class<? extends Log> getObjectType() {
return (this.log != null ? this.log.getClass() : Log.class);
}

View File

@@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single
*/
boolean isCacheBeanMetadata();
/**
* Specify the resolution strategy for expressions in bean definition values.
* <p>There is no expression support active in a BeanFactory by default.
* An ApplicationContext will typically set a standard expression strategy
* here, supporting "#{...}" expressions in a Unified EL compatible style.
*/
void setBeanExpressionResolver(BeanExpressionResolver resolver);
/**
* Return the resolution strategy for expressions in bean definition values.
*/
BeanExpressionResolver getBeanExpressionResolver();
/**
* Add a PropertyEditorRegistrar to be applied to all bean creation processes.
* <p>Such a registrar creates new PropertyEditor instances and registers them
@@ -141,22 +154,7 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single
* @param requiredType type of the property
* @param propertyEditorClass the {@link PropertyEditor} class to register
*/
void registerCustomEditor(Class requiredType, Class propertyEditorClass);
/**
* Register the given custom property editor for all properties of the
* given type. To be invoked during factory configuration.
* <p>Note that this method will register a shared custom editor instance;
* access to that instance will be synchronized for thread-safety. It is
* generally preferable to use {@link #addPropertyEditorRegistrar} instead
* of this method, to avoid for the need for synchronization on custom editors.
* @param requiredType type of the property
* @param propertyEditor editor to register
* @deprecated as of Spring 2.0.7, in favor of {@link #addPropertyEditorRegistrar}
* and {@link #registerCustomEditor(Class, Class)}
*/
@Deprecated
void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor);
void registerCustomEditor(Class requiredType, Class<PropertyEditor> propertyEditorClass);
/**
* Initialize the given PropertyEditorRegistry with the custom editors
@@ -186,7 +184,12 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single
/**
* Add a new BeanPostProcessor that will get applied to beans created
* by this factory. To be invoked during factory configuration.
* @param beanPostProcessor the bean processor to register
* <p>Note: Post-processors submitted here will be applied in the order of
* registration; any ordering semantics expressed through implementing the
* {@link org.springframework.core.Ordered} interface will be ignored. Note
* that autodetected post-processors (e.g. as beans in an ApplicationContext)
* will always be applied after programmatically registered ones.
* @param beanPostProcessor the post-processor to register
*/
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

View File

@@ -17,7 +17,6 @@
package org.springframework.beans.factory.config;
import java.beans.PropertyEditor;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
@@ -90,7 +89,7 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla
private PropertyEditorRegistrar[] propertyEditorRegistrars;
private Map customEditors;
private Map<String, String> customEditors;
private boolean ignoreUnresolvableEditors = false;
@@ -123,12 +122,10 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla
* Specify the custom editors to register via a {@link Map}, using the
* class name of the required type as the key and the class name of the
* associated {@link PropertyEditor} as value.
* <p>Also supports {@link PropertyEditor} instances as values; however,
* this is deprecated since Spring 2.0.7 and will be removed in Spring 3.0.
* @param customEditors said <code>Map</code> of editors (can be <code>null</code>)
* @param customEditors said <code>Map</code> of editors (can be <code>null</code>)
* @see ConfigurableListableBeanFactory#registerCustomEditor
*/
public void setCustomEditors(Map customEditors) {
public void setCustomEditors(Map<String, String> customEditors) {
this.customEditors = customEditors;
}
@@ -151,45 +148,21 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.propertyEditorRegistrars != null) {
for (int i = 0; i < this.propertyEditorRegistrars.length; i++) {
beanFactory.addPropertyEditorRegistrar(this.propertyEditorRegistrars[i]);
for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
beanFactory.addPropertyEditorRegistrar(propertyEditorRegistrar);
}
}
if (this.customEditors != null) {
for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
for (Map.Entry<String, String> entry : this.customEditors.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Class requiredType = null;
try {
if (key instanceof Class) {
requiredType = (Class) key;
}
else if (key instanceof String) {
requiredType = ClassUtils.forName((String) key, this.beanClassLoader);
}
else {
throw new IllegalArgumentException(
"Invalid key [" + key + "] for custom editor: needs to be Class or String.");
}
if (value instanceof PropertyEditor) {
beanFactory.registerCustomEditor(requiredType, (PropertyEditor) value);
}
else if (value instanceof Class) {
beanFactory.registerCustomEditor(requiredType, (Class) value);
}
else if (value instanceof String) {
Class editorClass = ClassUtils.forName((String) value, this.beanClassLoader);
beanFactory.registerCustomEditor(requiredType, editorClass);
}
else {
throw new IllegalArgumentException("Mapped value [" + value + "] for custom editor key [" +
key + "] is not of required type [" + PropertyEditor.class.getName() +
"] or a corresponding Class or String value indicating a PropertyEditor implementation");
}
requiredType = ClassUtils.forName(key, this.beanClassLoader);
Class editorClass = ClassUtils.forName(value, this.beanClassLoader);
beanFactory.registerCustomEditor(requiredType, editorClass);
}
catch (ClassNotFoundException ex) {
if (this.ignoreUnresolvableEditors) {

View File

@@ -16,15 +16,12 @@
package org.springframework.beans.factory.config;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.JdkVersion;
import org.springframework.core.MethodParameter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
/**
* Descriptor for a specific dependency that is about to be injected.
@@ -36,10 +33,6 @@ import org.springframework.util.ReflectionUtils;
*/
public class DependencyDescriptor {
private static final Method fieldAnnotationsMethod =
ClassUtils.getMethodIfAvailable(Field.class, "getAnnotations", new Class[0]);
private MethodParameter methodParameter;
private Field field;
@@ -48,7 +41,7 @@ public class DependencyDescriptor {
private final boolean eager;
private Object[] fieldAnnotations;
private Annotation[] fieldAnnotations;
/**
@@ -147,9 +140,6 @@ public class DependencyDescriptor {
* @return the generic type, or <code>null</code> if none
*/
public Class getCollectionType() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
return null;
}
return (this.field != null ?
GenericCollectionTypeResolver.getCollectionFieldType(this.field) :
GenericCollectionTypeResolver.getCollectionParameterType(this.methodParameter));
@@ -160,9 +150,6 @@ public class DependencyDescriptor {
* @return the generic type, or <code>null</code> if none
*/
public Class getMapKeyType() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
return null;
}
return (this.field != null ?
GenericCollectionTypeResolver.getMapKeyFieldType(this.field) :
GenericCollectionTypeResolver.getMapKeyParameterType(this.methodParameter));
@@ -173,9 +160,6 @@ public class DependencyDescriptor {
* @return the generic type, or <code>null</code> if none
*/
public Class getMapValueType() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
return null;
}
return (this.field != null ?
GenericCollectionTypeResolver.getMapValueFieldType(this.field) :
GenericCollectionTypeResolver.getMapValueParameterType(this.methodParameter));
@@ -183,20 +167,12 @@ public class DependencyDescriptor {
/**
* Obtain the annotations associated with the wrapped parameter/field, if any.
* @return the parameter/field annotations, or <code>null</code> if there is
* no annotation support (on JDK < 1.5). The return value is an Object array
* instead of an Annotation array simply for compatibility with older JDKs;
* feel free to cast it to <code>Annotation[]</code> on JDK 1.5 or higher.
*/
public Object[] getAnnotations() {
public Annotation[] getAnnotations() {
if (this.field != null) {
if (this.fieldAnnotations != null) {
return this.fieldAnnotations;
if (this.fieldAnnotations == null) {
this.fieldAnnotations = this.field.getAnnotations();
}
if (fieldAnnotationsMethod == null) {
return null;
}
this.fieldAnnotations = (Object[]) ReflectionUtils.invokeMethod(fieldAnnotationsMethod, this.field);
return this.fieldAnnotations;
}
else {

View File

@@ -83,7 +83,7 @@ public class ListFactoryBean extends AbstractFactoryBean {
result = new ArrayList(this.sourceList.size());
}
Class valueType = null;
if (this.targetListClass != null && JdkVersion.isAtLeastJava15()) {
if (this.targetListClass != null) {
valueType = GenericCollectionTypeResolver.getCollectionType(this.targetListClass);
}
if (valueType != null) {

View File

@@ -84,7 +84,7 @@ public class MapFactoryBean extends AbstractFactoryBean {
}
Class keyType = null;
Class valueType = null;
if (this.targetMapClass != null && JdkVersion.isAtLeastJava15()) {
if (this.targetMapClass != null) {
keyType = GenericCollectionTypeResolver.getMapKeyType(this.targetMapClass);
valueType = GenericCollectionTypeResolver.getMapValueType(this.targetMapClass);
}

View File

@@ -257,16 +257,16 @@ public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer
BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
for (int i = 0; i < beanNames.length; i++) {
for (String curName : beanNames) {
// Check that we're not parsing our own bean definition,
// to avoid failing on unresolvable placeholders in properties file locations.
if (!(beanNames[i].equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]);
if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName);
try {
visitor.visitBeanDefinition(bd);
}
catch (BeanDefinitionStoreException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i], ex.getMessage());
throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage());
}
}
}
@@ -287,10 +287,10 @@ public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer
* @throws BeanDefinitionStoreException if invalid values are encountered
* @see #resolvePlaceholder(String, java.util.Properties, int)
*/
protected String parseStringValue(String strVal, Properties props, Set visitedPlaceholders)
protected String parseStringValue(String strVal, Properties props, Set<String> visitedPlaceholders)
throws BeanDefinitionStoreException {
StringBuffer buf = new StringBuffer(strVal);
StringBuilder buf = new StringBuilder(strVal);
int startIndex = strVal.indexOf(this.placeholderPrefix);
while (startIndex != -1) {
@@ -443,7 +443,7 @@ public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer
}
public String resolveStringValue(String strVal) throws BeansException {
String value = parseStringValue(strVal, this.props, new HashSet());
String value = parseStringValue(strVal, this.props, new HashSet<String>());
return (value.equals(nullValue) ? null : value);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -118,6 +118,14 @@ public interface Scope {
*/
void registerDestructionCallback(String name, Runnable callback);
/**
* Resolve the contextual object for the given key, if any.
* E.g. the HttpServletRequest object for key "request".
* @param key the contextual key
* @return the corresponding object, or <code>null</code> if none found
*/
Object resolveContextualObject(String key);
/**
* Return the <em>conversation ID</em> for the current underlying scope, if any.
* <p>The exact meaning of the conversation ID depends on the underlying

View File

@@ -23,7 +23,6 @@ import java.util.Set;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.TypeConverter;
import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.JdkVersion;
/**
* Simple factory for shared Set instances. Allows for central setup
@@ -83,7 +82,7 @@ public class SetFactoryBean extends AbstractFactoryBean {
result = new LinkedHashSet(this.sourceSet.size());
}
Class valueType = null;
if (this.targetSetClass != null && JdkVersion.isAtLeastJava15()) {
if (this.targetSetClass != null) {
valueType = GenericCollectionTypeResolver.getCollectionType(this.targetSetClass);
}
if (valueType != null) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -95,7 +95,7 @@ public final class ParseState {
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
for (int x = 0; x < this.state.size(); x++) {
if (x > 0) {
sb.append('\n');

View File

@@ -116,7 +116,7 @@ public class Problem {
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
sb.append("Configuration problem: ");
sb.append(getMessage());
sb.append("\nOffending resource: ").append(getResourceDescription());

View File

@@ -35,6 +35,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
@@ -64,7 +65,6 @@ import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.core.CollectionFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.ClassUtils;
@@ -122,19 +122,21 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* Dependency types to ignore on dependency check and autowire, as Set of
* Class objects: for example, String. Default is none.
*/
private final Set ignoredDependencyTypes = new HashSet();
private final Set<Class> ignoredDependencyTypes = new HashSet<Class>();
/**
* Dependency interfaces to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/
private final Set ignoredDependencyInterfaces = new HashSet();
private final Set<Class> ignoredDependencyInterfaces = new HashSet<Class>();
/** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */
private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, BeanWrapper> factoryBeanInstanceCache =
new ConcurrentHashMap<String, BeanWrapper>();
/** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */
private final Map filteredPropertyDescriptorsCache = new HashMap();
private final Map<Class, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
new HashMap<Class, PropertyDescriptor[]>();
/**
@@ -346,8 +348,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
throws BeansException {
Object result = existingBean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
}
return result;
@@ -357,8 +358,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
throws BeansException {
Object result = existingBean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
}
return result;
@@ -379,7 +379,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
throws BeanCreationException {
AccessControlContext acc = AccessController.getContext();
return AccessController.doPrivileged(new PrivilegedAction() {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
@@ -436,7 +436,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName);
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
@@ -491,9 +491,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
for (int i = 0; i < dependentBeans.length; i++) {
String dependentBean = dependentBeans[i];
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
@@ -529,8 +528,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Apply SmartInstantiationAwareBeanPostProcessors to predict the
// eventual type after a before-instantiation shortcut.
if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {
BeanPostProcessor bp = (BeanPostProcessor) it.next();
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Class processedType = ibp.predictBeanType(beanClass, beanName);
@@ -584,9 +582,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Can't clearly figure out exact method due to type converting / autowiring!
int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount();
Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass);
Set returnTypes = new HashSet(1);
for (int i = 0; i < candidates.length; i++) {
Method factoryMethod = candidates[i];
Set<Class> returnTypes = new HashSet<Class>(1);
for (Method factoryMethod : candidates) {
if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
factoryMethod.getName().equals(mbd.getFactoryMethodName()) &&
factoryMethod.getParameterTypes().length >= minNrOfArgs) {
@@ -596,7 +593,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
if (returnTypes.size() == 1) {
// Clear return type found: all factory methods return same type.
return (Class) returnTypes.iterator().next();
return returnTypes.iterator().next();
}
else {
// Ambiguous return types found: return null to indicate "not determinable".
@@ -642,8 +639,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {
BeanPostProcessor bp = (BeanPostProcessor) it.next();
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
@@ -669,7 +665,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
*/
private FactoryBean getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
synchronized (getSingletonMutex()) {
BeanWrapper bw = (BeanWrapper) this.factoryBeanInstanceCache.get(beanName);
BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
if (bw != null) {
return (FactoryBean) bw.getWrappedInstance();
}
@@ -742,10 +738,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class beanType, String beanName)
throws BeansException {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
if (beanProcessor instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) beanProcessor;
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
@@ -768,7 +763,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
mbd.beforeInstantiationResolved = Boolean.valueOf(bean != null);
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
@@ -788,10 +783,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName)
throws BeansException {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor;
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
@@ -856,10 +850,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
if (beanProcessor instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) beanProcessor;
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
@@ -956,10 +949,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor;
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
@@ -995,10 +987,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw);
if (hasInstAwareBpps) {
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor;
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
@@ -1027,15 +1018,15 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (int i = 0; i < propertyNames.length; i++) {
String propertyName = propertyNames[i];
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.addPropertyValue(propertyName, bean);
registerDependentBean(propertyName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
logger.debug(
"Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName +
"' to bean named '" + propertyName + "'");
}
}
else {
@@ -1066,10 +1057,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
converter = bw;
}
Set autowiredBeanNames = new LinkedHashSet(4);
Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (int i = 0; i < propertyNames.length; i++) {
String propertyName = propertyNames[i];
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
@@ -1081,12 +1071,12 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
if (autowiredArgument != null) {
pvs.addPropertyValue(propertyName, autowiredArgument);
}
for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) {
String autowiredBeanName = (String) it.next();
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
logger.debug(
"Autowiring by type from bean name '" + beanName + "' via property '" + propertyName +
"' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
@@ -1108,13 +1098,13 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* @see org.springframework.beans.BeanUtils#isSimpleProperty
*/
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
Set result = new TreeSet();
Set<String> result = new TreeSet<String>();
PropertyValues pvs = mbd.getPropertyValues();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
if (pds[i].getWriteMethod() != null && !isExcludedFromDependencyCheck(pds[i]) &&
!pvs.contains(pds[i].getName()) && !BeanUtils.isSimpleProperty(pds[i].getPropertyType())) {
result.add(pds[i].getName());
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
result.add(pd.getName());
}
}
return StringUtils.toStringArray(result);
@@ -1130,17 +1120,17 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
*/
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) {
synchronized (this.filteredPropertyDescriptorsCache) {
PropertyDescriptor[] filtered = (PropertyDescriptor[])
this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
if (filtered == null) {
List pds = new LinkedList(Arrays.asList(bw.getPropertyDescriptors()));
List<PropertyDescriptor> pds =
new LinkedList<PropertyDescriptor>(Arrays.asList(bw.getPropertyDescriptors()));
for (Iterator it = pds.iterator(); it.hasNext();) {
PropertyDescriptor pd = (PropertyDescriptor) it.next();
if (isExcludedFromDependencyCheck(pd)) {
it.remove();
}
}
filtered = (PropertyDescriptor[]) pds.toArray(new PropertyDescriptor[pds.size()]);
filtered = pds.toArray(new PropertyDescriptor[pds.size()]);
this.filteredPropertyDescriptorsCache.put(bw.getWrappedClass(), filtered);
}
return filtered;
@@ -1178,15 +1168,14 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
throws UnsatisfiedDependencyException {
int dependencyCheck = mbd.getDependencyCheck();
for (int i = 0; i < pds.length; i++) {
if (pds[i].getWriteMethod() != null && !pvs.contains(pds[i].getName())) {
boolean isSimple = BeanUtils.isSimpleProperty(pds[i].getPropertyType());
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null && !pvs.contains(pd.getName())) {
boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) ||
(isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
(!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
(isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
(!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
if (unsatisfied) {
throw new UnsatisfiedDependencyException(
mbd.getResourceDescription(), beanName, pds[i].getName(),
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
"Set this property value or disable dependency checking for this bean.");
}
}
@@ -1208,7 +1197,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
MutablePropertyValues mpvs = null;
List original = null;
List<PropertyValue> original = null;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
@@ -1236,10 +1225,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
List deepCopy = new ArrayList(original.size());
List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
for (Iterator it = original.iterator(); it.hasNext();) {
PropertyValue pv = (PropertyValue) it.next();
for (PropertyValue pv : original) {
if (pv.isConverted()) {
deepCopy.add(pv);
}

View File

@@ -985,7 +985,7 @@ public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccess
@Override
public String toString() {
StringBuffer sb = new StringBuffer("class [");
StringBuilder sb = new StringBuilder("class [");
sb.append(getBeanClassName()).append("]");
sb.append("; scope=").append(this.scope);
sb.append("; abstract=").append(this.abstractFlag);

View File

@@ -22,11 +22,11 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
@@ -51,12 +51,13 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.CollectionFactory;
import org.springframework.core.DecoratingClassLoader;
import org.springframework.core.NamedThreadLocal;
import org.springframework.util.Assert;
@@ -108,17 +109,22 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
/** Whether to cache bean metadata or rather reobtain it for every access */
private boolean cacheBeanMetadata = true;
/** Custom PropertyEditorRegistrars to apply to the beans of this factory */
private final Set propertyEditorRegistrars = new LinkedHashSet(4);
/** Resolution strategy for expressions in bean definition values */
private BeanExpressionResolver beanExpressionResolver;
/** Custom PropertyEditors to apply to the beans of this factory */
private final Map customEditors = new HashMap(4);
/** Custom PropertyEditorRegistrars to apply to the beans of this factory */
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars =
new LinkedHashSet<PropertyEditorRegistrar>(4);
/** A custom TypeConverter to use, overriding the default PropertyEditor mechanism */
private TypeConverter typeConverter;
/** Custom PropertyEditors to apply to the beans of this factory */
private final Map<Class, Class<PropertyEditor>> customEditors =
new HashMap<Class, Class<PropertyEditor>>(4);
/** BeanPostProcessors to apply in createBean */
private final List beanPostProcessors = new ArrayList();
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
/** Indicates whether any InstantiationAwareBeanPostProcessors have been registered */
private boolean hasInstantiationAwareBeanPostProcessors;
@@ -127,18 +133,18 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
private boolean hasDestructionAwareBeanPostProcessors;
/** Map from scope identifier String to corresponding Scope */
private final Map scopes = new HashMap();
private final Map<String, Scope> scopes = new HashMap<String, Scope>();
/** Map from bean name to merged RootBeanDefinition */
private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, RootBeanDefinition> mergedBeanDefinitions =
new ConcurrentHashMap<String, RootBeanDefinition>();
/** Names of beans that have already been created at least once */
private final Set alreadyCreated = Collections.synchronizedSet(new HashSet());
private final Set<String> alreadyCreated = Collections.synchronizedSet(new HashSet<String>());
/** Names of beans that are currently in creation */
private final ThreadLocal prototypesCurrentlyInCreation =
new NamedThreadLocal("Prototype beans currently in creation");
private final ThreadLocal<Object> prototypesCurrentlyInCreation =
new NamedThreadLocal<Object>("Prototype beans currently in creation");
/**
* Create a new AbstractBeanFactory.
@@ -164,7 +170,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
return getBean(name, null, null);
}
public Object getBean(String name, Class requiredType) throws BeansException {
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return getBean(name, requiredType, null);
}
@@ -181,7 +187,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
public Object getBean(String name, Class requiredType, Object[] args) throws BeansException {
public <T> T getBean(String name, Class<T> requiredType, Object[] args) throws BeansException {
return doGetBean(name, requiredType, args, false);
}
@@ -196,8 +202,9 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
protected Object doGetBean(
final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean = null;
@@ -231,7 +238,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return parentBeanFactory.getBean(nameToLookup, args);
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
@@ -249,8 +256,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (int i = 0; i < dependsOn.length; i++) {
String dependsOnBean = dependsOn[i];
for (String dependsOnBean : dependsOn) {
getBean(dependsOnBean);
registerDependentBean(dependsOnBean, beanName);
}
@@ -290,7 +296,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
else {
String scopeName = mbd.getScope();
final Scope scope = (Scope) this.scopes.get(scopeName);
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
}
@@ -321,7 +327,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return bean;
return (T) bean;
}
public boolean containsBean(String name) {
@@ -505,7 +511,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
@Override
public String[] getAliases(String name) {
String beanName = transformedBeanName(name);
List aliases = new ArrayList();
List<String> aliases = new ArrayList<String>();
boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
String fullBeanName = beanName;
if (factoryPrefix) {
@@ -515,8 +521,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
aliases.add(fullBeanName);
}
String[] retrievedAliases = super.getAliases(beanName);
for (int i = 0; i < retrievedAliases.length; i++) {
String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAliases[i];
for (String retrievedAliase : retrievedAliases) {
String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAliase;
if (!alias.equals(name)) {
aliases.add(alias);
}
@@ -581,6 +587,14 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
return this.cacheBeanMetadata;
}
public void setBeanExpressionResolver(BeanExpressionResolver resolver) {
this.beanExpressionResolver = resolver;
}
public BeanExpressionResolver getBeanExpressionResolver() {
return this.beanExpressionResolver;
}
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
this.propertyEditorRegistrars.add(registrar);
@@ -589,31 +603,24 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
/**
* Return the set of PropertyEditorRegistrars.
*/
public Set getPropertyEditorRegistrars() {
public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
public void registerCustomEditor(Class requiredType, Class propertyEditorClass) {
public void registerCustomEditor(Class requiredType, Class<PropertyEditor> propertyEditorClass) {
Assert.notNull(requiredType, "Required type must not be null");
Assert.isAssignable(PropertyEditor.class, propertyEditorClass);
this.customEditors.put(requiredType, propertyEditorClass);
}
public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) {
Assert.notNull(requiredType, "Required type must not be null");
Assert.notNull(propertyEditor, "PropertyEditor must not be null");
this.customEditors.put(requiredType, propertyEditor);
}
public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
registerCustomEditors(registry);
}
/**
* Return the map of custom editors, with Classes as keys
* and PropertyEditor instances or PropertyEditor classes as values.
* Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.
*/
public Map getCustomEditors() {
public Map<Class, Class<PropertyEditor>> getCustomEditors() {
return this.customEditors;
}
@@ -661,7 +668,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* Return the list of BeanPostProcessors that will get applied
* to beans created with this factory.
*/
public List getBeanPostProcessors() {
public List<BeanPostProcessor> getBeanPostProcessors() {
return this.beanPostProcessors;
}
@@ -700,13 +707,14 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
public Scope getRegisteredScope(String scopeName) {
Assert.notNull(scopeName, "Scope identifier must not be null");
return (Scope) this.scopes.get(scopeName);
return this.scopes.get(scopeName);
}
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
Assert.notNull(otherFactory, "BeanFactory must not be null");
setBeanClassLoader(otherFactory.getBeanClassLoader());
setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
if (otherFactory instanceof AbstractBeanFactory) {
AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
this.customEditors.putAll(otherAbstractFactory.customEditors);
@@ -718,6 +726,9 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
this.scopes.putAll(otherAbstractFactory.scopes);
}
else {
setTypeConverter(otherFactory.getTypeConverter());
}
}
/**
@@ -771,13 +782,13 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
this.prototypesCurrentlyInCreation.set(beanName);
}
else if (curVal instanceof String) {
Set beanNameSet = new HashSet(2);
beanNameSet.add(curVal);
Set<String> beanNameSet = new HashSet<String>(2);
beanNameSet.add((String) curVal);
beanNameSet.add(beanName);
this.prototypesCurrentlyInCreation.set(beanNameSet);
}
else {
Set beanNameSet = (Set) curVal;
Set<String> beanNameSet = (Set<String>) curVal;
beanNameSet.add(beanName);
}
}
@@ -794,7 +805,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
this.prototypesCurrentlyInCreation.set(null);
}
else if (curVal instanceof Set) {
Set beanNameSet = (Set) curVal;
Set<String> beanNameSet = (Set<String>) curVal;
beanNameSet.remove(beanName);
if (beanNameSet.isEmpty()) {
this.prototypesCurrentlyInCreation.set(null);
@@ -839,7 +850,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
"Bean name '" + beanName + "' does not correspond to an object in a Scope");
}
String scopeName = mbd.getScope();
Scope scope = (Scope) this.scopes.get(scopeName);
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
}
@@ -904,8 +915,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
registrySupport.useConfigValueEditors();
}
if (!this.propertyEditorRegistrars.isEmpty()) {
for (Iterator it = this.propertyEditorRegistrars.iterator(); it.hasNext();) {
PropertyEditorRegistrar registrar = (PropertyEditorRegistrar) it.next();
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
@@ -916,8 +926,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
if (isCurrentlyInCreation(bce.getBeanName())) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" + ex.getBeanName() +
"': " + ex.getMessage());
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
continue;
@@ -928,28 +938,11 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
}
}
if (!this.customEditors.isEmpty()) {
for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Class requiredType = (Class) entry.getKey();
Object value = entry.getValue();
if (value instanceof PropertyEditor) {
PropertyEditor editor = (PropertyEditor) value;
// Register the editor as shared instance, if possible,
// to make it clear that it might be used concurrently.
if (registrySupport != null) {
registrySupport.registerSharedEditor(requiredType, editor);
}
else {
registry.registerCustomEditor(requiredType, editor);
}
}
else if (value instanceof Class) {
Class editorClass = (Class) value;
registry.registerCustomEditor(requiredType, (PropertyEditor) BeanUtils.instantiateClass(editorClass));
}
else {
throw new IllegalStateException("Illegal custom editor value type: " + value.getClass().getName());
}
for (Map.Entry<Class, Class<PropertyEditor>> entry : this.customEditors.entrySet()) {
Class requiredType = entry.getKey();
Class editorClass = entry.getValue();
registry.registerCustomEditor(requiredType,
(PropertyEditor) BeanUtils.instantiateClass(editorClass));
}
}
}
@@ -965,7 +958,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
*/
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
RootBeanDefinition mbd = (RootBeanDefinition) this.mergedBeanDefinitions.get(beanName);
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null) {
return mbd;
}
@@ -1005,7 +998,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = (RootBeanDefinition) this.mergedBeanDefinitions.get(beanName);
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
@@ -1128,8 +1121,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
if (tempClassLoader != null) {
if (tempClassLoader instanceof DecoratingClassLoader) {
DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
for (int i = 0; i < typesToMatch.length; i++) {
dcl.excludeClass(typesToMatch[i].getName());
for (Class typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
String className = mbd.getBeanClassName();
@@ -1146,6 +1139,22 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
}
}
/**
* Evaluate the given String as contained in a bean definition,
* potentially resolving it as an expression.
* @param value the value to check
* @param beanDefinition the bean definition that the value comes from
* @return the resolved value
* @see #setBeanExpressionResolver
*/
protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) {
if (this.beanExpressionResolver == null) {
return value;
}
Scope scope = getRegisteredScope(beanDefinition.getScope());
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
/**
* Predict the eventual bean type (of the processed bean instance) for the
@@ -1199,8 +1208,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
return null;
}
try {
FactoryBean factoryBean =
(FactoryBean) doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
FactoryBean factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
return getTypeForFactoryBean(factoryBean);
}
catch (BeanCreationException ex) {
@@ -1339,7 +1347,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
}
else {
// A bean with a custom scope...
Scope scope = (Scope) this.scopes.get(mbd.getScope());
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'");
}

View File

@@ -22,10 +22,8 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import org.springframework.core.JdkVersion;
import org.springframework.util.ClassUtils;
/**
@@ -39,10 +37,6 @@ import org.springframework.util.ClassUtils;
*/
abstract class AutowireUtils {
private static final String QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME =
"org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver";
/**
* Sort the given constructors, preferring public constructors and "greedy" ones
* with a maximum of arguments. The result will contain public constructors first,
@@ -51,10 +45,8 @@ abstract class AutowireUtils {
* @param constructors the constructor array to sort
*/
public static void sortConstructors(Constructor[] constructors) {
Arrays.sort(constructors, new Comparator() {
public int compare(Object o1, Object o2) {
Constructor c1 = (Constructor) o1;
Constructor c2 = (Constructor) o2;
Arrays.sort(constructors, new Comparator<Constructor>() {
public int compare(Constructor c1, Constructor c2) {
boolean p1 = Modifier.isPublic(c1.getModifiers());
boolean p2 = Modifier.isPublic(c2.getModifiers());
if (p1 != p2) {
@@ -62,7 +54,7 @@ abstract class AutowireUtils {
}
int c1pl = c1.getParameterTypes().length;
int c2pl = c2.getParameterTypes().length;
return (new Integer(c1pl)).compareTo(new Integer(c2pl)) * -1;
return (new Integer(c1pl)).compareTo(c2pl) * -1;
}
});
}
@@ -78,7 +70,7 @@ abstract class AutowireUtils {
if (wm == null) {
return false;
}
if (wm.getDeclaringClass().getName().indexOf("$$") == -1) {
if (!wm.getDeclaringClass().getName().contains("$$")) {
// Not a CGLIB method so it's OK.
return false;
}
@@ -95,12 +87,11 @@ abstract class AutowireUtils {
* @param interfaces the Set of interfaces (Class objects)
* @return whether the setter method is defined by an interface
*/
public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set interfaces) {
public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set<Class> interfaces) {
Method setter = pd.getWriteMethod();
if (setter != null) {
Class targetClass = setter.getDeclaringClass();
for (Iterator it = interfaces.iterator(); it.hasNext();) {
Class ifc = (Class) it.next();
for (Class ifc : interfaces) {
if (ifc.isAssignableFrom(targetClass) &&
ClassUtils.hasMethod(ifc, setter.getName(), setter.getParameterTypes())) {
return true;
@@ -110,25 +101,4 @@ abstract class AutowireUtils {
return false;
}
/**
* If at least Java 1.5, this will return an annotation-aware resolver.
* Otherwise it returns a resolver that checks the bean definition only.
*/
public static AutowireCandidateResolver createAutowireCandidateResolver() {
if (JdkVersion.isAtLeastJava15()) {
try {
Class resolverClass = ClassUtils.forName(
QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME, AutowireUtils.class.getClassLoader());
return (AutowireCandidateResolver) resolverClass.newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException("Unable to load Java 1.5 dependent class [" +
QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME + "]", ex);
}
}
else {
return new SimpleAutowireCandidateResolver();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,15 +38,6 @@ import org.springframework.core.io.ResourceLoader;
*/
public interface BeanDefinitionReader {
/**
* Return the bean factory to register the bean definitions with.
* <p>The factory is exposed through the BeanDefinitionRegistry interface,
* encapsulating the methods that are relevant for bean definition handling.
* @deprecated in favor of the uniformly named {@link #getRegistry()}
*/
@Deprecated
BeanDefinitionRegistry getBeanFactory();
/**
* Return the bean factory to register the bean definitions with.
* <p>The factory is exposed through the BeanDefinitionRegistry interface,

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,31 +45,6 @@ public class BeanDefinitionReaderUtils {
public static final String GENERATED_BEAN_NAME_SEPARATOR = BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR;
/**
* Create a new GenericBeanDefinition for the given
* class name, parent, constructor arguments, and property values.
* @param className the name of the bean class, if any
* @param parentName the name of the parent bean, if any
* @param cargs the constructor arguments, if any
* @param pvs the property values, if any
* @param classLoader the ClassLoader to use for loading bean classes
* (can be <code>null</code> to just register bean classes by name)
* @return the bean definition
* @throws ClassNotFoundException if the bean class could not be loaded
* @deprecated in favor of <code>createBeanDefinition(String, String, ClassLoader)</code>
* @see #createBeanDefinition(String, String, ClassLoader)
*/
@Deprecated
public static AbstractBeanDefinition createBeanDefinition(
String className, String parentName, ConstructorArgumentValues cargs,
MutablePropertyValues pvs, ClassLoader classLoader) throws ClassNotFoundException {
AbstractBeanDefinition bd = createBeanDefinition(parentName, className, classLoader);
bd.setConstructorArgumentValues(cargs);
bd.setPropertyValues(pvs);
return bd;
}
/**
* Create a new GenericBeanDefinition for the given parent name and class name,
* eagerly loading the bean class if a ClassLoader has been specified.

View File

@@ -17,7 +17,6 @@
package org.springframework.beans.factory.support;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -104,12 +103,13 @@ class BeanDefinitionValueResolver {
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) {
String ref = ((RuntimeBeanNameReference) value).getBeanName();
if (!this.beanFactory.containsBean(ref)) {
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(evaluate(refName));
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + ref + "' in bean reference for " + argName);
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return ref;
return refName;
}
else if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
@@ -123,21 +123,20 @@ class BeanDefinitionValueResolver {
}
else if (value instanceof ManagedList) {
// May need to resolve contained runtime references.
return resolveManagedList(argName, (List) value);
return resolveManagedList(argName, (List<?>) value);
}
else if (value instanceof ManagedSet) {
// May need to resolve contained runtime references.
return resolveManagedSet(argName, (Set) value);
return resolveManagedSet(argName, (Set<?>) value);
}
else if (value instanceof ManagedMap) {
// May need to resolve contained runtime references.
return resolveManagedMap(argName, (Map) value);
return resolveManagedMap(argName, (Map<?, ?>) value);
}
else if (value instanceof ManagedProperties) {
Properties original = (Properties) value;
Properties copy = new Properties();
for (Iterator it = original.entrySet().iterator(); it.hasNext();) {
Map.Entry propEntry = (Map.Entry) it.next();
for (Map.Entry propEntry : original.entrySet()) {
Object propKey = propEntry.getKey();
Object propValue = propEntry.getValue();
if (propKey instanceof TypedStringValue) {
@@ -153,14 +152,14 @@ class BeanDefinitionValueResolver {
else if (value instanceof TypedStringValue) {
// Convert value to target type here.
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue.getValue());
try {
Class resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) {
return this.typeConverter.convertIfNecessary(typedStringValue.getValue(), resolvedTargetType);
return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
else {
// No target type specified - no conversion necessary...
return typedStringValue.getValue();
return valueObject;
}
}
catch (Throwable ex) {
@@ -171,7 +170,20 @@ class BeanDefinitionValueResolver {
}
}
else {
// No need to resolve value...
return evaluate(value);
}
}
/**
* Evaluate the given value as an expression, if necessary.
* @param value the candidate value (may be an expression)
* @return the resolved value
*/
protected Object evaluate(Object value) {
if (value instanceof String) {
return this.beanFactory.evaluateBeanDefinitionString((String) value, this.beanDefinition);
}
else {
return value;
}
}
@@ -210,8 +222,7 @@ class BeanDefinitionValueResolver {
// Guarantee initialization of beans that the inner bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (int i = 0; i < dependsOn.length; i++) {
String dependsOnBean = dependsOn[i];
for (String dependsOnBean : dependsOn) {
this.beanFactory.getBean(dependsOnBean);
this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName);
}
@@ -256,18 +267,20 @@ class BeanDefinitionValueResolver {
*/
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
String refName = ref.getBeanName();
refName = String.valueOf(evaluate(refName));
if (ref.isToParent()) {
if (this.beanFactory.getParentBeanFactory() == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Can't resolve reference to bean '" + ref.getBeanName() +
"Can't resolve reference to bean '" + refName +
"' in parent factory: no parent factory available");
}
return this.beanFactory.getParentBeanFactory().getBean(ref.getBeanName());
return this.beanFactory.getParentBeanFactory().getBean(refName);
}
else {
Object bean = this.beanFactory.getBean(ref.getBeanName());
this.beanFactory.registerDependentBean(ref.getBeanName(), this.beanName);
Object bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
return bean;
}
}
@@ -281,7 +294,7 @@ class BeanDefinitionValueResolver {
/**
* For each element in the ManagedList, resolve reference if necessary.
*/
private List resolveManagedList(Object argName, List ml) {
private List resolveManagedList(Object argName, List<?> ml) {
List resolved = new ArrayList(ml.size());
for (int i = 0; i < ml.size(); i++) {
resolved.add(
@@ -295,14 +308,12 @@ class BeanDefinitionValueResolver {
/**
* For each element in the ManagedList, resolve reference if necessary.
*/
private Set resolveManagedSet(Object argName, Set ms) {
private Set resolveManagedSet(Object argName, Set<?> ms) {
Set resolved = new LinkedHashSet(ms.size());
int i = 0;
for (Iterator it = ms.iterator(); it.hasNext();) {
resolved.add(
resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX,
it.next()));
for (Object m : ms) {
resolved.add(resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX, m));
i++;
}
return resolved;
@@ -311,15 +322,13 @@ class BeanDefinitionValueResolver {
/**
* For each element in the ManagedMap, resolve reference if necessary.
*/
private Map resolveManagedMap(Object argName, Map mm) {
private Map resolveManagedMap(Object argName, Map<?, ?> mm) {
Map resolved = new LinkedHashMap(mm.size());
Iterator it = mm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
for (Map.Entry entry : mm.entrySet()) {
Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey());
Object resolvedValue = resolveValueIfNecessary(
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + entry.getKey() + BeanWrapper.PROPERTY_KEY_SUFFIX,
entry.getValue());
argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + entry.getKey() +
BeanWrapper.PROPERTY_KEY_SUFFIX, entry.getValue());
resolved.put(resolvedKey, resolvedValue);
}
return resolved;

View File

@@ -172,7 +172,7 @@ public class ChildBeanDefinition extends AbstractBeanDefinition {
@Override
public String toString() {
StringBuffer sb = new StringBuffer("Child bean with parent '");
StringBuilder sb = new StringBuilder("Child bean with parent '");
sb.append(this.parentName).append("': ").append(super.toString());
return sb.toString();
}

View File

@@ -41,7 +41,6 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.JdkVersion;
import org.springframework.core.MethodParameter;
import org.springframework.util.MethodInvoker;
import org.springframework.util.ObjectUtils;
@@ -131,9 +130,7 @@ class ConstructorResolver {
for (int i = 0; i < argsToResolve.length; i++) {
Object argValue = argsToResolve[i];
MethodParameter methodParam = new MethodParameter(constructorToUse, i);
if (JdkVersion.isAtLeastJava15()) {
GenericTypeResolver.resolveParameterType(methodParam, constructorToUse.getDeclaringClass());
}
GenericTypeResolver.resolveParameterType(methodParam, constructorToUse.getDeclaringClass());
if (argValue instanceof AutowiredArgumentMarker) {
argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
}
@@ -318,9 +315,7 @@ class ConstructorResolver {
for (int i = 0; i < argsToResolve.length; i++) {
Object argValue = argsToResolve[i];
MethodParameter methodParam = new MethodParameter(factoryMethodToUse, i);
if (JdkVersion.isAtLeastJava15()) {
GenericTypeResolver.resolveParameterType(methodParam, factoryClass);
}
GenericTypeResolver.resolveParameterType(methodParam, factoryClass);
if (argValue instanceof AutowiredArgumentMarker) {
argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
}

View File

@@ -19,11 +19,11 @@ package org.springframework.beans.factory.support;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
@@ -38,12 +38,12 @@ import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.CollectionFactory;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
@@ -91,19 +91,19 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
private boolean configurationFrozen = false;
/** Map of bean definition objects, keyed by bean name */
private final Map beanDefinitionMap = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
/** List of bean definition names, in registration order */
private final List beanDefinitionNames = new ArrayList();
private final List<String> beanDefinitionNames = new ArrayList<String>();
/** Cached array of bean definition names in case of frozen configuration */
private String[] frozenBeanDefinitionNames;
/** Resolver to use for checking if a bean definition is an autowire candidate */
private AutowireCandidateResolver autowireCandidateResolver = AutowireUtils.createAutowireCandidateResolver();
private AutowireCandidateResolver autowireCandidateResolver = new QualifierAnnotationAutowireCandidateResolver();
/** Map from dependency type to corresponding autowired value */
private final Map resolvableDependencies = new HashMap();
private final Map<Class, Object> resolvableDependencies = new HashMap<Class, Object>();
/**
@@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) {
List result = new ArrayList();
List<String> result = new ArrayList<String>();
// Check all bean definitions.
String[] beanDefinitionNames = getBeanDefinitionNames();
for (int i = 0; i < beanDefinitionNames.length; i++) {
String beanName = beanDefinitionNames[i];
for (String beanName : beanDefinitionNames) {
// Only consider bean as eligible if the bean name
// is not defined as alias for some other bean.
if (!isAlias(beanName)) {
try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// Only check bean definition if it is complete.
if (!mbd.isAbstract() &&
(allowEagerInit || ((mbd.hasBeanClass() || !mbd.isLazyInit() || this.allowEagerClassLoading)) &&
if (!mbd.isAbstract() && (allowEagerInit ||
((mbd.hasBeanClass() || !mbd.isLazyInit() || this.allowEagerClassLoading)) &&
!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
// In case of FactoryBean, match object created by FactoryBean.
boolean isFactoryBean = isFactoryBean(beanName, mbd);
boolean matchFound =
(allowEagerInit || !isFactoryBean || containsSingleton(beanName)) &&
boolean matchFound = (allowEagerInit || !isFactoryBean || containsSingleton(beanName)) &&
(includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type);
if (!matchFound && isFactoryBean) {
// In case of FactoryBean, try to match FactoryBean instance itself next.
@@ -260,8 +258,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
// Check singletons too, to catch manually registered singletons.
String[] singletonNames = getSingletonNames();
for (int i = 0; i < singletonNames.length; i++) {
String beanName = singletonNames[i];
for (String beanName : singletonNames) {
// Only check if manually registered.
if (!containsBeanDefinition(beanName)) {
// In case of FactoryBean, match object created by FactoryBean.
@@ -295,19 +292,18 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName));
}
public Map getBeansOfType(Class type) throws BeansException {
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
return getBeansOfType(type, true, true);
}
public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit)
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
Map result = new LinkedHashMap(beanNames.length);
for (int i = 0; i < beanNames.length; i++) {
String beanName = beanNames[i];
Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
for (String beanName : beanNames) {
try {
result.put(beanName, getBean(beanName));
result.put(beanName, getBean(beanName, type));
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
@@ -315,7 +311,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
BeanCreationException bce = (BeanCreationException) rootCause;
if (isCurrentlyInCreation(bce.getBeanName())) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " + ex.getMessage());
this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " +
ex.getMessage());
}
onSuppressedException(ex);
// Ignore: indicates a circular reference when autowiring constructors.
@@ -382,7 +379,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
@Override
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(beanName);
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("No bean named '" + beanName + "' found in " + this);
@@ -419,8 +416,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
synchronized (this.beanDefinitionMap) {
for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) {
String beanName = (String) it.next();
for (String beanName : this.beanDefinitionNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
@@ -487,7 +483,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
Assert.hasText(beanName, "'beanName' must not be empty");
synchronized (this.beanDefinitionMap) {
BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.remove(beanName);
BeanDefinition bd = this.beanDefinitionMap.remove(beanName);
if (bd == null) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("No bean named '" + beanName + "' found in " + this);
@@ -519,10 +515,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
// Reset all bean definitions that have the given bean as parent
// (recursively).
for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) {
String bdName = (String) it.next();
for (String bdName : this.beanDefinitionNames) {
if (!beanName.equals(bdName)) {
BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(bdName);
BeanDefinition bd = this.beanDefinitionMap.get(bdName);
if (beanName.equals(bd.getParentName())) {
resetBeanDefinition(bdName);
}
@@ -544,12 +539,12 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
//---------------------------------------------------------------------
public Object resolveDependency(DependencyDescriptor descriptor, String beanName,
Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
Class type = descriptor.getDependencyType();
if (type.isArray()) {
Class componentType = type.getComponentType();
Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor);
@@ -570,7 +565,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
return null;
}
Map matchingBeans = findAutowireCandidates(beanName, elementType, descriptor);
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, descriptor);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor);
@@ -599,7 +594,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
return null;
}
Map matchingBeans = findAutowireCandidates(beanName, valueType, descriptor);
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor);
@@ -612,7 +607,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return matchingBeans;
}
else {
Map matchingBeans = findAutowireCandidates(beanName, type, descriptor);
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
throw new NoSuchBeanDefinitionException(type,
@@ -632,7 +627,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return matchingBeans.get(primaryBeanName);
}
// We have exactly one match.
Map.Entry entry = (Map.Entry) matchingBeans.entrySet().iterator().next();
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
if (autowiredBeanNames != null) {
autowiredBeanNames.add(entry.getKey());
}
@@ -653,12 +648,13 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
* @see #autowireByType
* @see #autowireConstructor
*/
protected Map findAutowireCandidates(String beanName, Class requiredType, DependencyDescriptor descriptor) {
protected Map<String, Object> findAutowireCandidates(
String beanName, Class requiredType, DependencyDescriptor descriptor) {
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
Map result = new LinkedHashMap(candidateNames.length);
for (Iterator it = this.resolvableDependencies.keySet().iterator(); it.hasNext();) {
Class autowiringType = (Class) it.next();
Map<String, Object> result = new LinkedHashMap<String, Object>(candidateNames.length);
for (Class autowiringType : this.resolvableDependencies.keySet()) {
if (autowiringType.isAssignableFrom(requiredType)) {
Object autowiringValue = this.resolvableDependencies.get(autowiringType);
if (autowiringValue instanceof ObjectFactory && !requiredType.isInstance(autowiringValue)) {
@@ -670,8 +666,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
}
for (int i = 0; i < candidateNames.length; i++) {
String candidateName = candidateNames[i];
for (String candidateName : candidateNames) {
if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) {
result.put(candidateName, getBean(candidateName));
}
@@ -686,11 +681,10 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
* @param type the required type
* @return the name of the primary candidate, or <code>null</code> if none found
*/
protected String determinePrimaryCandidate(Map candidateBeans, Class type) {
protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, Class type) {
String primaryBeanName = null;
for (Iterator it = candidateBeans.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String candidateBeanName = (String) entry.getKey();
for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
String candidateBeanName = entry.getKey();
if (isPrimary(candidateBeanName, entry.getValue())) {
if (primaryBeanName != null) {
throw new NoSuchBeanDefinitionException(type,
@@ -736,7 +730,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
@Override
public String toString() {
StringBuffer sb = new StringBuffer(ObjectUtils.identityToString(this));
StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this));
sb.append(": defining beans [");
sb.append(StringUtils.arrayToCommaDelimitedString(getBeanDefinitionNames()));
sb.append("]; ");
@@ -745,7 +739,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
sb.append("root of factory hierarchy");
}
else {
sb.append("parent: " + ObjectUtils.identityToString(parent));
sb.append("parent: ").append(ObjectUtils.identityToString(parent));
}
return sb.toString();
}

View File

@@ -24,6 +24,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -34,7 +35,6 @@ import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.core.CollectionFactory;
import org.springframework.core.SimpleAliasRegistry;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -83,37 +83,37 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
protected final Log logger = LogFactory.getLog(getClass());
/** Cache of singleton objects: bean name --> bean instance */
private final Map singletonObjects = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>();
/** Cache of singleton factories: bean name --> ObjectFactory */
private final Map singletonFactories = new HashMap();
private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>();
/** Cache of early singleton objects: bean name --> bean instance */
private final Map earlySingletonObjects = new HashMap();
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>();
/** Set of registered singletons, containing the bean names in registration order */
private final Set registeredSingletons = new LinkedHashSet(16);
private final Set<String> registeredSingletons = new LinkedHashSet<String>(16);
/** Names of beans that are currently in creation */
private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet());
private final Set<String> singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet<String>());
/** List of suppressed Exceptions, available for associating related causes */
private Set suppressedExceptions;
private Set<Exception> suppressedExceptions;
/** Flag that indicates whether we're currently within destroySingletons */
private boolean singletonsCurrentlyInDestruction = false;
/** Disposable bean instances: bean name --> disposable instance */
private final Map disposableBeans = new LinkedHashMap(16);
private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
/** Map between containing bean names: bean name --> Set of bean names that the bean contains */
private final Map containedBeanMap = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>();
/** Map between dependent bean names: bean name --> Set of dependent bean names */
private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>();
/** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */
private final Map dependenciesForBeanMap = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>();
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
@@ -180,7 +180,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory singletonFactory = (ObjectFactory) this.singletonFactories.get(beanName);
ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
@@ -216,15 +216,15 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
beforeSingletonCreation(beanName);
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet();
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
singletonObject = singletonFactory.getObject();
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Iterator it = this.suppressedExceptions.iterator(); it.hasNext();) {
ex.addRelatedCause((Exception) it.next());
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
@@ -346,9 +346,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
*/
public void registerContainedBean(String containedBeanName, String containingBeanName) {
synchronized (this.containedBeanMap) {
Set containedBeans = (Set) this.containedBeanMap.get(containingBeanName);
Set<String> containedBeans = this.containedBeanMap.get(containingBeanName);
if (containedBeans == null) {
containedBeans = new LinkedHashSet(8);
containedBeans = new LinkedHashSet<String>(8);
this.containedBeanMap.put(containingBeanName, containedBeans);
}
containedBeans.add(containedBeanName);
@@ -364,17 +364,17 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
synchronized (this.dependentBeanMap) {
Set dependentBeans = (Set) this.dependentBeanMap.get(beanName);
Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
if (dependentBeans == null) {
dependentBeans = new LinkedHashSet(8);
dependentBeans = new LinkedHashSet<String>(8);
this.dependentBeanMap.put(beanName, dependentBeans);
}
dependentBeans.add(dependentBeanName);
}
synchronized (this.dependenciesForBeanMap) {
Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName);
Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
if (dependenciesForBean == null) {
dependenciesForBean = new LinkedHashSet(8);
dependenciesForBean = new LinkedHashSet<String>(8);
this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
}
dependenciesForBean.add(beanName);
@@ -395,11 +395,11 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
* @return the array of dependent bean names, or an empty array if none
*/
public String[] getDependentBeans(String beanName) {
Set dependentBeans = (Set) this.dependentBeanMap.get(beanName);
Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
if (dependentBeans == null) {
return new String[0];
}
return (String[]) dependentBeans.toArray(new String[dependentBeans.size()]);
return StringUtils.toStringArray(dependentBeans);
}
/**
@@ -409,11 +409,11 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
* or an empty array if none
*/
public String[] getDependenciesForBean(String beanName) {
Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(beanName);
Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
if (dependenciesForBean == null) {
return new String[0];
}
return (String[]) dependenciesForBean.toArray(new String[dependenciesForBean.size()]);
return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);
}
public void destroySingletons() {
@@ -470,13 +470,12 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
*/
protected void destroyBean(String beanName, DisposableBean bean) {
// Trigger destruction of dependent beans first...
Set dependencies = (Set) this.dependentBeanMap.remove(beanName);
Set<String> dependencies = this.dependentBeanMap.remove(beanName);
if (dependencies != null) {
if (logger.isDebugEnabled()) {
logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
}
for (Iterator it = dependencies.iterator(); it.hasNext();) {
String dependentBeanName = (String) it.next();
for (String dependentBeanName : dependencies) {
destroySingleton(dependentBeanName);
}
}
@@ -492,10 +491,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
}
// Trigger destruction of contained beans...
Set containedBeans = (Set) this.containedBeanMap.remove(beanName);
Set<String> containedBeans = this.containedBeanMap.remove(beanName);
if (containedBeans != null) {
for (Iterator it = containedBeans.iterator(); it.hasNext();) {
String containedBeanName = (String) it.next();
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}

View File

@@ -20,13 +20,13 @@ import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.FactoryBeanNotInitializedException;
import org.springframework.core.CollectionFactory;
/**
* Support base class for singleton registries which need to handle
@@ -41,7 +41,7 @@ import org.springframework.core.CollectionFactory;
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
/** Cache of singleton objects created by FactoryBeans: FactoryBean name --> object */
private final Map factoryBeanObjectCache = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>();
/**
@@ -113,7 +113,7 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg
throws BeanCreationException {
AccessControlContext acc = AccessController.getContext();
return AccessController.doPrivileged(new PrivilegedAction() {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
Object object;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@ import org.springframework.beans.Mergeable;
* @author Juergen Hoeller
* @since 27.05.2003
*/
public class ManagedList extends ArrayList implements Mergeable, BeanMetadataElement {
public class ManagedList<E> extends ArrayList<E> implements Mergeable, BeanMetadataElement {
private Object source;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ import org.springframework.beans.Mergeable;
* @author Rob Harrop
* @since 27.05.2003
*/
public class ManagedMap extends LinkedHashMap implements Mergeable, BeanMetadataElement {
public class ManagedMap<K, V> extends LinkedHashMap<K, V> implements Mergeable, BeanMetadataElement {
private Object source;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.beans.factory.support;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -32,7 +30,7 @@ import org.springframework.beans.Mergeable;
* @author Rob Harrop
* @since 21.01.2004
*/
public class ManagedSet extends LinkedHashSet implements Mergeable, BeanMetadataElement {
public class ManagedSet<E> extends LinkedHashSet<E> implements Mergeable, BeanMetadataElement {
private Object source;

View File

@@ -21,7 +21,6 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
@@ -93,12 +92,6 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
*/
public static final String CLASS_KEY = "(class)";
/**
* Special key to distinguish <code>owner.class=com.myapp.MyClass</code>.
* Deprecated in favor of .(class)=
*/
private static final String DEPRECATED_CLASS_KEY = "class";
/**
* Special key to distinguish <code>owner.(parent)=parentBeanName</code>.
*/
@@ -295,7 +288,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
*/
public int registerBeanDefinitions(ResourceBundle rb, String prefix) throws BeanDefinitionStoreException {
// Simply create a map and call overloaded method.
Map map = new HashMap();
Map<String, Object> map = new HashMap<String, Object>();
Enumeration keys = rb.getKeys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
@@ -356,8 +349,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
}
int beanCount = 0;
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
Object key = it.next();
for (Object key : map.keySet()) {
if (!(key instanceof String)) {
throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed");
}
@@ -408,7 +400,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
* Map came from (for logging purposes)
* @throws BeansException if the bean definition could not be parsed or registered
*/
protected void registerBeanDefinition(String beanName, Map map, String prefix, String resourceDescription)
protected void registerBeanDefinition(String beanName, Map<?, ?> map, String prefix, String resourceDescription)
throws BeansException {
String className = null;
@@ -420,12 +412,11 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
ConstructorArgumentValues cas = new ConstructorArgumentValues();
MutablePropertyValues pvs = new MutablePropertyValues();
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
for (Map.Entry entry : map.entrySet()) {
String key = StringUtils.trimWhitespace((String) entry.getKey());
if (key.startsWith(prefix + SEPARATOR)) {
String property = key.substring(prefix.length() + SEPARATOR.length());
if (isClassKey(property)) {
if (CLASS_KEY.equals(property)) {
className = StringUtils.trimWhitespace((String) entry.getValue());
}
else if (PARENT_KEY.equals(property)) {
@@ -442,8 +433,8 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
else if (SINGLETON_KEY.equals(property)) {
// Spring 1.2 style
String val = StringUtils.trimWhitespace((String) entry.getValue());
scope = ((val == null || TRUE_VALUE.equals(val) ?
GenericBeanDefinition.SCOPE_SINGLETON : GenericBeanDefinition.SCOPE_PROTOTYPE));
scope = ((val == null || TRUE_VALUE.equals(val) ? GenericBeanDefinition.SCOPE_SINGLETON :
GenericBeanDefinition.SCOPE_PROTOTYPE));
}
else if (LAZY_INIT_KEY.equals(property)) {
String val = StringUtils.trimWhitespace((String) entry.getValue());
@@ -470,7 +461,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
Object val = new RuntimeBeanReference(ref);
pvs.addPropertyValue(property, val);
}
else{
else {
// It's a normal bean property.
pvs.addPropertyValue(property, readValue(entry));
}
@@ -506,23 +497,6 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader
}
}
/**
* Indicates whether the supplied property matches the class property of
* the bean definition.
*/
private boolean isClassKey(String property) {
if (CLASS_KEY.equals(property)) {
return true;
}
else if (DEPRECATED_CLASS_KEY.equals(property)) {
if (logger.isWarnEnabled()) {
logger.warn("Use of 'class' property in [" + getClass().getName() + "] is deprecated in favor of '(class)'");
}
return true;
}
return false;
}
/**
* Reads the value of the entry. Correctly interprets bean references for
* values that are prefixed with an asterisk.

View File

@@ -17,11 +17,11 @@
package org.springframework.beans.factory.support;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.core.CollectionFactory;
import org.springframework.core.SimpleAliasRegistry;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -37,7 +37,7 @@ import org.springframework.util.StringUtils;
public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements BeanDefinitionRegistry {
/** Map of bean definition objects, keyed by bean name */
private final Map beanDefinitionMap = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
@@ -55,7 +55,7 @@ public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements
}
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(beanName);
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
throw new NoSuchBeanDefinitionException(beanName);
}

View File

@@ -66,11 +66,11 @@ import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
/**
* Stateful delegate class used to parse XML bean definitions. Intended for use
* by both the main parser and any extension
* Stateful delegate class used to parse XML bean definitions.
* Intended for use by both the main parser and any extension
* {@link BeanDefinitionParser BeanDefinitionParsers} or
* {@link BeanDefinitionDecorator BeanDefinitionDecorators}.
*
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Rod Johnson
@@ -86,8 +86,8 @@ public class BeanDefinitionParserDelegate {
public static final String BEAN_NAME_DELIMITERS = ",; ";
/**
* Value of a T/F attribute that represents true. Anything else represents
* false. Case seNsItive.
* Value of a T/F attribute that represents true.
* Anything else represents false. Case seNsItive.
*/
public static final String TRUE_VALUE = "true";
@@ -227,6 +227,7 @@ public class BeanDefinitionParserDelegate {
public static final String DEFAULT_DESTROY_METHOD_ATTRIBUTE = "default-destroy-method";
protected final Log logger = LogFactory.getLog(getClass());
private final XmlReaderContext readerContext;
@@ -236,15 +237,14 @@ public class BeanDefinitionParserDelegate {
private ParseState parseState = new ParseState();
/**
* Stores all used bean names so we can enforce uniqueness on a per file
* basis.
* Stores all used bean names so we can enforce uniqueness on a per file basis.
*/
private final Set usedNames = new HashSet();
/**
* Create a new BeanDefinitionParserDelegate associated with the supplied
* {@link XmlReaderContext}.
* Create a new BeanDefinitionParserDelegate associated with the
* supplied {@link XmlReaderContext}.
*/
public BeanDefinitionParserDelegate(XmlReaderContext readerContext) {
Assert.notNull(readerContext, "XmlReaderContext must not be null");
@@ -258,10 +258,10 @@ public class BeanDefinitionParserDelegate {
return this.readerContext;
}
/**
* Invoke the
* {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull
* the source metadata from the supplied {@link Element}.
* Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull the
* source metadata from the supplied {@link Element}.
*/
protected Object extractSource(Element ele) {
return this.readerContext.extractSource(ele);
@@ -288,10 +288,10 @@ public class BeanDefinitionParserDelegate {
this.readerContext.error(message, source, this.parseState.snapshot(), cause);
}
/**
* Initialize the default lazy-init, autowire, dependency check settings,
* init-method, destroy-method and merge settings.
*
* @see #getDefaults()
*/
public void initDefaults(Element root) {
@@ -324,8 +324,8 @@ public class BeanDefinitionParserDelegate {
}
/**
* Return the default settings for bean definitions as indicated within the
* attributes of the top-level <code>&lt;beans/&gt;</code> element.
* Return the default settings for bean definitions as indicated within
* the attributes of the top-level <code>&lt;beans/&gt;</code> element.
*/
public BeanDefinitionDefaults getBeanDefinitionDefaults() {
BeanDefinitionDefaults bdd = new BeanDefinitionDefaults();
@@ -348,10 +348,10 @@ public class BeanDefinitionParserDelegate {
return candidatePattern == null ? null : StringUtils.commaDelimitedListToStringArray(candidatePattern);
}
/**
* Parses the supplied <code>&lt;bean&gt;</code> element. May return
* <code>null</code> if there were errors during parse. Errors are
* reported to the
* Parses the supplied <code>&lt;bean&gt;</code> element. May return <code>null</code>
* if there were errors during parse. Errors are reported to the
* {@link org.springframework.beans.factory.parsing.ProblemReporter}.
*/
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
@@ -359,9 +359,8 @@ public class BeanDefinitionParserDelegate {
}
/**
* Parses the supplied <code>&lt;bean&gt;</code> element. May return
* <code>null</code> if there were errors during parse. Errors are
* reported to the
* Parses the supplied <code>&lt;bean&gt;</code> element. May return <code>null</code>
* if there were errors during parse. Errors are reported to the
* {@link org.springframework.beans.factory.parsing.ProblemReporter}.
*/
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
@@ -378,8 +377,8 @@ public class BeanDefinitionParserDelegate {
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = (String) aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases
+ " as aliases");
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
@@ -392,8 +391,8 @@ public class BeanDefinitionParserDelegate {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition,
this.readerContext.getRegistry(), true);
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
beanName = this.readerContext.generateBeanName(beanDefinition);
@@ -401,15 +400,15 @@ public class BeanDefinitionParserDelegate {
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null && beanName.startsWith(beanClassName)
&& beanName.length() > beanClassName.length()
&& !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " + "using generated bean name ["
+ beanName + "]");
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
@@ -425,8 +424,7 @@ public class BeanDefinitionParserDelegate {
}
/**
* Validate that the specified bean name and aliases have not been used
* already.
* Validate that the specified bean name and aliases have not been used already.
*/
protected void checkNameUniqueness(String beanName, List aliases, Element beanElement) {
String foundName = null;
@@ -446,11 +444,11 @@ public class BeanDefinitionParserDelegate {
}
/**
* Parse the bean definition itself, without regard to name or aliases. May
* return <code>null</code> if problems occured during the parse of the
* bean definition.
* Parse the bean definition itself, without regard to name or aliases. May return
* <code>null</code> if problems occured during the parse of the bean definition.
*/
public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) {
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
@@ -467,7 +465,6 @@ public class BeanDefinitionParserDelegate {
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
@@ -500,14 +497,11 @@ public class BeanDefinitionParserDelegate {
}
/**
* Apply the attributes of the given bean element to the given bean
* definition.
*
* Apply the attributes of the given bean element to the given bean * definition.
* @param ele bean declaration element
* @param beanName bean name
* @param containingBean containing bean definition
* @return a bean definition initialized according to the bean element
* attributes
* @return a bean definition initialized according to the bean element attributes
*/
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
BeanDefinition containingBean, AbstractBeanDefinition bd) {
@@ -605,18 +599,16 @@ public class BeanDefinitionParserDelegate {
/**
* Create a bean definition for the given class name and parent name.
*
* @param className the name of the bean class
* @param parentName the name of the bean's parent bean
* @return the newly created bean definition
* @throws ClassNotFoundException if bean class resolution was attempted but
* failed
* @throws ClassNotFoundException if bean class resolution was attempted but failed
*/
protected AbstractBeanDefinition createBeanDefinition(String className, String parentName)
throws ClassNotFoundException {
return BeanDefinitionReaderUtils.createBeanDefinition(parentName, className,
this.readerContext.getBeanClassLoader());
return BeanDefinitionReaderUtils.createBeanDefinition(
parentName, className, this.readerContext.getBeanClassLoader());
}
public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
@@ -772,8 +764,7 @@ public class BeanDefinitionParserDelegate {
try {
this.parseState.push(new ConstructorArgumentEntry(index));
Object value = parsePropertyValue(ele, bd, null);
ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(
value);
ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
if (StringUtils.hasLength(typeAttr)) {
valueHolder.setType(typeAttr);
}
@@ -875,20 +866,21 @@ public class BeanDefinitionParserDelegate {
}
/**
* Get the value of a property element. May be a list etc. Also used for
* constructor arguments, "propertyName" being null in this case.
* Get the value of a property element. May be a list etc.
* Also used for constructor arguments, "propertyName" being null in this case.
*/
public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
String elementName = (propertyName != null) ? "<property> element for property '" + propertyName + "'"
: "<constructor-arg> element";
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
// Should only have one child element: ref, value, list, etc.
NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT)
&& !DomUtils.nodeNameEquals(node, META_ELEMENT)) {
if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
!DomUtils.nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
@@ -901,9 +893,10 @@ public class BeanDefinitionParserDelegate {
boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
if ((hasRefAttribute && hasValueAttribute) || ((hasRefAttribute || hasValueAttribute) && subElement != null)) {
error(elementName
+ " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
if ((hasRefAttribute && hasValueAttribute) ||
((hasRefAttribute || hasValueAttribute) && subElement != null)) {
error(elementName +
" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
}
if (hasRefAttribute) {
@@ -937,7 +930,6 @@ public class BeanDefinitionParserDelegate {
/**
* Parse a value, ref or collection sub-element of a property or
* constructor-arg element.
*
* @param ele subelement of property element; we don't know which yet
* @param defaultTypeClassName the default type (class name) for any
* <code>&lt;value&gt;</code> tag that might be created
@@ -1011,10 +1003,6 @@ public class BeanDefinitionParserDelegate {
/**
* Return a typed String value Object for the given 'idref' element.
*
* @param ele
* @param bd
* @return
*/
public Object parseIdRefElement(Element ele) {
// A generic reference to any name of any bean.
@@ -1038,10 +1026,6 @@ public class BeanDefinitionParserDelegate {
/**
* Return a typed String value Object for the given value element.
*
* @param ele element
* @param defaultTypeClassName type class name
* @return typed String value Object
*/
public Object parseValueElement(Element ele, String defaultTypeClassName) {
// It's a literal value.
@@ -1061,7 +1045,6 @@ public class BeanDefinitionParserDelegate {
/**
* Build a typed String value Object for the given raw value.
*
* @see org.springframework.beans.factory.config.TypedStringValue
*/
protected Object buildTypedStringValue(String value, String targetTypeName, Element ele)
@@ -1167,13 +1150,14 @@ public class BeanDefinitionParserDelegate {
Object key = null;
boolean hasKeyAttribute = entryEle.hasAttribute(KEY_ATTRIBUTE);
boolean hasKeyRefAttribute = entryEle.hasAttribute(KEY_REF_ATTRIBUTE);
if ((hasKeyAttribute && hasKeyRefAttribute) || ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) {
error("<entry> element is only allowed to contain either "
+ "a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element", entryEle);
if ((hasKeyAttribute && hasKeyRefAttribute) ||
((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) {
error("<entry> element is only allowed to contain either " +
"a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element", entryEle);
}
if (hasKeyAttribute) {
key = buildTypedStringValueForMap(entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyTypeClassName,
entryEle);
key = buildTypedStringValueForMap(
entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyTypeClassName, entryEle);
}
else if (hasKeyRefAttribute) {
String refName = entryEle.getAttribute(KEY_REF_ATTRIBUTE);
@@ -1195,14 +1179,14 @@ public class BeanDefinitionParserDelegate {
Object value = null;
boolean hasValueAttribute = entryEle.hasAttribute(VALUE_ATTRIBUTE);
boolean hasValueRefAttribute = entryEle.hasAttribute(VALUE_REF_ATTRIBUTE);
if ((hasValueAttribute && hasValueRefAttribute) || ((hasValueAttribute || hasValueRefAttribute))
&& valueEle != null) {
error("<entry> element is only allowed to contain either "
+ "'value' attribute OR 'value-ref' attribute OR <value> sub-element", entryEle);
if ((hasValueAttribute && hasValueRefAttribute) ||
((hasValueAttribute || hasValueRefAttribute)) && valueEle != null) {
error("<entry> element is only allowed to contain either " +
"'value' attribute OR 'value-ref' attribute OR <value> sub-element", entryEle);
}
if (hasValueAttribute) {
value = buildTypedStringValueForMap(entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueTypeClassName,
entryEle);
value = buildTypedStringValueForMap(
entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueTypeClassName, entryEle);
}
else if (hasValueRefAttribute) {
String refName = entryEle.getAttribute(VALUE_REF_ATTRIBUTE);
@@ -1229,7 +1213,6 @@ public class BeanDefinitionParserDelegate {
/**
* Build a typed String value Object for the given raw value.
*
* @see org.springframework.beans.factory.config.TypedStringValue
*/
protected final Object buildTypedStringValueForMap(String value, String defaultTypeClassName, Element entryEle) {
@@ -1318,8 +1301,8 @@ public class BeanDefinitionParserDelegate {
return decorateBeanDefinitionIfRequired(ele, definitionHolder, null);
}
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder,
BeanDefinition containingBd) {
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) {
BeanDefinitionHolder finalDefinition = definitionHolder;
@@ -1341,8 +1324,8 @@ public class BeanDefinitionParserDelegate {
return finalDefinition;
}
private BeanDefinitionHolder decorateIfRequired(Node node, BeanDefinitionHolder originalDef,
BeanDefinition containingBd) {
private BeanDefinitionHolder decorateIfRequired(
Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) {
String namespaceUri = node.getNamespaceURI();
if (!isDefaultNamespace(namespaceUri)) {
@@ -1370,15 +1353,17 @@ public class BeanDefinitionParserDelegate {
private BeanDefinitionHolder parseNestedCustomElement(Element ele, BeanDefinition containingBd) {
BeanDefinition innerDefinition = parseCustomElement(ele, containingBd);
if (innerDefinition == null) {
error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. "
+ "This tag cannot be used nested inside <property>.", ele);
error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " +
"This tag cannot be used nested inside <property>.", ele);
return null;
}
String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR
+ ObjectUtils.getIdentityHexString(innerDefinition);
String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR +
ObjectUtils.getIdentityHexString(innerDefinition);
if (logger.isDebugEnabled()) {
logger.debug("Using generated bean name [" + id + "] for nested custom element '" + ele.getNodeName() + "'");
logger.debug("Using generated bean name [" + id +
"] for nested custom element '" + ele.getNodeName() + "'");
}
return new BeanDefinitionHolder(innerDefinition, id);
}
}

View File

@@ -155,10 +155,8 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver
this.handlerMappings = new HashMap(mappings);
}
catch (IOException ex) {
IllegalStateException ise = new IllegalStateException(
"Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]");
ise.initCause(ex);
throw ise;
throw new IllegalStateException(
"Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex);
}
}
return this.handlerMappings;

View File

@@ -1,58 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.xml;
import org.w3c.dom.Document;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.core.io.Resource;
/**
* Strategy interface for parsing XML bean definitions.
* Used by XmlBeanDefinitionReader for actually parsing a DOM document.
*
* <p>Instantiated per document to parse: Implementations can hold
* state in instance variables during the execution of the
* <code>registerBeanDefinitions</code> method, for example global
* settings that are defined for all bean definitions in the document.
*
* @author Juergen Hoeller
* @since 18.12.2003
* @deprecated as of Spring 2.0: superseded by BeanDefinitionDocumentReader
* @see BeanDefinitionDocumentReader
* @see XmlBeanDefinitionReader#setParserClass
*/
@Deprecated
public interface XmlBeanDefinitionParser {
/**
* Parse bean definitions from the given DOM document,
* and register them with the given bean factory.
* @param reader the bean definition reader, containing the bean factory
* to work on and the bean class loader to use. Can also be used to load
* further bean definition files referenced by the given document.
* @param doc the DOM document
* @param resource descriptor of the original XML resource
* (useful for displaying parse errors)
* @return the number of bean definitions found
* @throws BeanDefinitionStoreException in case of parsing errors
*/
int registerBeanDefinitions(BeanDefinitionReader reader, Document doc, Resource resource)
throws BeanDefinitionStoreException;
}

View File

@@ -20,7 +20,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
@@ -104,8 +103,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
private int validationMode = VALIDATION_AUTO;
private Class parserClass;
private Class documentReaderClass = DefaultBeanDefinitionDocumentReader.class;
private ProblemReporter problemReporter = new FailFastProblemReporter();
@@ -124,8 +121,8 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
private final XmlValidationModeDetector validationModeDetector = new XmlValidationModeDetector();
private final ThreadLocal resourcesCurrentlyBeingLoaded =
new NamedThreadLocal("XML bean definition resources currently being loaded");
private final ThreadLocal<Set<EncodedResource>> resourcesCurrentlyBeingLoaded =
new NamedThreadLocal<Set<EncodedResource>>("XML bean definition resources currently being loaded");
/**
@@ -153,16 +150,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
return this.namespaceAware;
}
/**
* Set if the XML parser should validate the document and thus enforce a DTD.
* @deprecated as of Spring 2.0: superseded by "validationMode"
* @see #setValidationMode
*/
@Deprecated
public void setValidating(boolean validating) {
this.validationMode = (validating ? VALIDATION_AUTO : VALIDATION_NONE);
}
/**
* Set the validation mode to use by name. Defaults to {@link #VALIDATION_AUTO}.
*/
@@ -270,21 +257,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
this.errorHandler = errorHandler;
}
/**
* Set the XmlBeanDefinitionParser implementation to use,
* responsible for the actual parsing of XML bean definitions.
* @deprecated as of Spring 2.0: superseded by "documentReaderClass"
* @see #setDocumentReaderClass
* @see XmlBeanDefinitionParser
*/
@Deprecated
public void setParserClass(Class parserClass) {
if (this.parserClass == null || !XmlBeanDefinitionParser.class.isAssignableFrom(parserClass)) {
throw new IllegalArgumentException("'parserClass' must be an XmlBeanDefinitionParser");
}
this.parserClass = parserClass;
}
/**
* Specify the BeanDefinitionDocumentReader implementation to use,
* responsible for the actual reading of the XML bean definition document.
@@ -325,9 +297,9 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set currentResources = (Set) this.resourcesCurrentlyBeingLoaded.get();
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet(4);
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
@@ -497,12 +469,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
* @see BeanDefinitionDocumentReader#registerBeanDefinitions
*/
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
// Support old XmlBeanDefinitionParser SPI for backwards-compatibility.
if (this.parserClass != null) {
XmlBeanDefinitionParser parser =
(XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass);
return parser.registerBeanDefinitions(this, doc, resource);
}
// Read document based on new BeanDefinitionDocumentReader SPI.
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
@@ -513,11 +479,12 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
/**
* Create the {@link BeanDefinitionDocumentReader} to use for actually
* reading bean definitions from an XML document.
* <p>Default implementation instantiates the specified "documentReaderClass".
* <p>The default implementation instantiates the specified "documentReaderClass".
* @see #setDocumentReaderClass
*/
@SuppressWarnings("unchecked")
protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
return (BeanDefinitionDocumentReader) BeanUtils.instantiateClass(this.documentReaderClass);
return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,14 +84,14 @@ public class ClassArrayEditor extends PropertyEditorSupport {
private static String toCommaDelimitedString(Class[] classes) {
StringBuffer buffer = new StringBuffer();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < classes.length; ++i) {
if (i > 0) {
buffer.append(",");
sb.append(",");
}
buffer.append(ClassUtils.getQualifiedName(classes[i]));
sb.append(ClassUtils.getQualifiedName(classes[i]));
}
return buffer.toString();
return sb.toString();
}
}

View File

@@ -107,10 +107,7 @@ public class CustomDateEditor extends PropertyEditorSupport {
setValue(this.dateFormat.parse(text));
}
catch (ParseException ex) {
IllegalArgumentException iae =
new IllegalArgumentException("Could not parse date: " + ex.getMessage());
iae.initCause(ex);
throw iae;
throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
}
}
}