diff --git a/org.springframework.aop/aop.iml b/org.springframework.aop/aop.iml index c3670a9e8f8..c366ae70a66 100644 --- a/org.springframework.aop/aop.iml +++ b/org.springframework.aop/aop.iml @@ -1,111 +1,111 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java index 441e69b22b7..d25616741b6 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java @@ -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. @@ -36,7 +36,6 @@ import org.springframework.aop.interceptor.ExposeInvocationInterceptor; import org.springframework.aop.support.ComposablePointcut; import org.springframework.aop.support.MethodMatchers; import org.springframework.aop.support.StaticMethodMatcher; -import org.springframework.core.JdkVersion; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.PrioritizedParameterNameDiscoverer; @@ -136,7 +135,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence */ private int joinPointStaticPartArgumentIndex = -1; - private Map argumentBindings = null; + private Map argumentBindings = null; private boolean argumentsIntrospected = false; @@ -454,7 +453,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence } private void bindExplicitArguments(int numArgumentsLeftToBind) { - this.argumentBindings = new HashMap(); + this.argumentBindings = new HashMap(); int numExpectedArgumentNames = this.aspectJAdviceMethod.getParameterTypes().length; if (this.argumentNames.length != numExpectedArgumentNames) { @@ -466,7 +465,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence // So we match in number... int argumentIndexOffset = this.adviceInvocationArgumentCount - numArgumentsLeftToBind; for (int i = argumentIndexOffset; i < this.argumentNames.length; i++) { - this.argumentBindings.put(this.argumentNames[i],new Integer(i)); + this.argumentBindings.put(this.argumentNames[i], i); } // Check that returning and throwing were in the argument names list if @@ -477,12 +476,9 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence + this.returningName + "' was not bound in advice arguments"); } else { - Integer index = (Integer) this.argumentBindings.get(this.returningName); - this.discoveredReturningType = this.aspectJAdviceMethod.getParameterTypes()[index.intValue()]; - if (JdkVersion.isAtLeastJava15()) { - this.discoveredReturningGenericType = - this.aspectJAdviceMethod.getGenericParameterTypes()[index.intValue()]; - } + Integer index = this.argumentBindings.get(this.returningName); + this.discoveredReturningType = this.aspectJAdviceMethod.getParameterTypes()[index]; + this.discoveredReturningGenericType = this.aspectJAdviceMethod.getGenericParameterTypes()[index]; } } if (this.throwingName != null) { @@ -491,8 +487,8 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence + this.throwingName + "' was not bound in advice arguments"); } else { - Integer index = (Integer) this.argumentBindings.get(this.throwingName); - this.discoveredThrowingType = this.aspectJAdviceMethod.getParameterTypes()[index.intValue()]; + Integer index = this.argumentBindings.get(this.throwingName); + this.discoveredThrowingType = this.aspectJAdviceMethod.getParameterTypes()[index]; } } @@ -564,24 +560,23 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence // binding from pointcut match if (jpMatch != null) { PointcutParameter[] parameterBindings = jpMatch.getParameterBindings(); - for (int i = 0; i < parameterBindings.length; i++) { - PointcutParameter parameter = parameterBindings[i]; + for (PointcutParameter parameter : parameterBindings) { String name = parameter.getName(); - Integer index = (Integer) this.argumentBindings.get(name); - adviceInvocationArgs[index.intValue()] = parameter.getBinding(); + Integer index = this.argumentBindings.get(name); + adviceInvocationArgs[index] = parameter.getBinding(); numBound++; } } // binding from returning clause if (this.returningName != null) { - Integer index = (Integer) this.argumentBindings.get(this.returningName); - adviceInvocationArgs[index.intValue()] = returnValue; + Integer index = this.argumentBindings.get(this.returningName); + adviceInvocationArgs[index] = returnValue; numBound++; } // binding from thrown exception if (this.throwingName != null) { - Integer index = (Integer) this.argumentBindings.get(this.throwingName); - adviceInvocationArgs[index.intValue()] = ex; + Integer index = this.argumentBindings.get(this.throwingName); + adviceInvocationArgs[index] = ex; numBound++; } } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java index f983be0110c..31c6471673e 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java @@ -655,7 +655,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov return new PointcutBody(0, currentToken.substring(bodyStart + 1, currentToken.length() - 1)); } else { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (bodyStart >= 0 && bodyStart != (currentToken.length() - 1)) { sb.append(currentToken.substring(bodyStart + 1)); sb.append(" "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java index 6df302bd6ca..a51ae393673 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java @@ -411,7 +411,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("AspectJExpressionPointcut: "); if (this.pointcutParameterNames != null && this.pointcutParameterTypes != null) { sb.append("("); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java index be4a5aadbaa..76e9c47535b 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java @@ -146,7 +146,7 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); Advice advice = this.advisor.getAdvice(); sb.append(ClassUtils.getShortName(advice.getClass())); sb.append(": "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java b/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java index 6b4dffb6d94..36eda243298 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java @@ -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. @@ -78,14 +78,14 @@ public class AdvisorComponentDefinition extends AbstractComponentDefinition { } private String buildDescription(BeanReference adviceReference, BeanDefinition pointcutDefinition) { - return new StringBuffer("Advisor ").toString(); } private String buildDescription(BeanReference adviceReference, BeanReference pointcutReference) { - return new StringBuffer("Advisor ").toString(); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java index ce796cc430b..201518315bd 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java @@ -20,10 +20,10 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.aopalliance.aop.Advice; @@ -36,7 +36,6 @@ import org.springframework.aop.support.DefaultIntroductionAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.target.EmptyTargetSource; import org.springframework.aop.target.SingletonTargetSource; -import org.springframework.core.CollectionFactory; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -80,19 +79,19 @@ public class AdvisedSupport extends ProxyConfig implements Advised { AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory(); /** Cache with Method as key and advisor chain List as value */ - private transient Map methodCache; + private transient Map> methodCache; /** * Interfaces to be implemented by the proxy. Held in List to keep the order * of registration, to create JDK proxy with specified order of interfaces. */ - private List interfaces = new ArrayList(); + private List interfaces = new ArrayList(); /** * List of Advisors. If an Advice is added, it will be wrapped * in an Advisor before being added to this List. */ - private List advisors = new LinkedList(); + private List advisors = new LinkedList(); /** * Array updated on changes to the advisors list, which is easier @@ -121,7 +120,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * Initialize the method cache. */ private void initMethodCache() { - this.methodCache = CollectionFactory.createConcurrentMapIfPossible(32); + this.methodCache = new ConcurrentHashMap>(32); } @@ -195,8 +194,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { public void setInterfaces(Class[] interfaces) { Assert.notNull(interfaces, "Interfaces must not be null"); this.interfaces.clear(); - for (int i = 0; i < interfaces.length; i++) { - addInterface(interfaces[i]); + for (Class ifc : interfaces) { + addInterface(ifc); } } @@ -227,12 +226,11 @@ public class AdvisedSupport extends ProxyConfig implements Advised { } public Class[] getProxiedInterfaces() { - return (Class[]) this.interfaces.toArray(new Class[this.interfaces.size()]); + return this.interfaces.toArray(new Class[this.interfaces.size()]); } public boolean isInterfaceProxied(Class intf) { - for (Iterator it = this.interfaces.iterator(); it.hasNext();) { - Class proxyIntf = (Class) it.next(); + for (Class proxyIntf : this.interfaces) { if (intf.isAssignableFrom(proxyIntf)) { return true; } @@ -277,7 +275,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { "This configuration only has " + this.advisors.size() + " advisors."); } - Advisor advisor = (Advisor) this.advisors.get(index); + Advisor advisor = this.advisors.get(index); if (advisor instanceof IntroductionAdvisor) { IntroductionAdvisor ia = (IntroductionAdvisor) advisor; // We need to remove introduction interfaces. @@ -317,8 +315,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { throw new AopConfigException("Cannot add advisor: Configuration is frozen."); } if (!ObjectUtils.isEmpty(advisors)) { - for (int i = 0; i < advisors.length; i++) { - Advisor advisor = advisors[i]; + for (Advisor advisor : advisors) { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } @@ -334,8 +331,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { advisor.validateInterfaces(); // If the advisor passed validation, we can make the change. Class[] ifcs = advisor.getInterfaces(); - for (int i = 0; i < ifcs.length; i++) { - addInterface(ifcs[i]); + for (Class ifc : ifcs) { + addInterface(ifc); } } @@ -357,7 +354,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * Bring the array up to date with the list. */ protected final void updateAdvisorArray() { - this.advisorArray = (Advisor[]) this.advisors.toArray(new Advisor[this.advisors.size()]); + this.advisorArray = this.advisors.toArray(new Advisor[this.advisors.size()]); } /** @@ -408,7 +405,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { public int indexOf(Advice advice) { Assert.notNull(advice, "Advice must not be null"); for (int i = 0; i < this.advisors.size(); i++) { - Advisor advisor = (Advisor) this.advisors.get(i); + Advisor advisor = this.advisors.get(i); if (advisor.getAdvice() == advice) { return i; } @@ -422,11 +419,11 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @return whether this advice instance is included */ public boolean adviceIncluded(Advice advice) { - Assert.notNull(advice, "Advice must not be null"); - for (int i = 0; i < this.advisors.size(); i++) { - Advisor advisor = (Advisor) this.advisors.get(i); - if (advisor.getAdvice() == advice) { - return true; + if (advice != null) { + for (Advisor advisor : this.advisors) { + if (advisor.getAdvice() == advice) { + return true; + } } } return false; @@ -438,13 +435,12 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @return the count of the interceptors of this class or subclasses */ public int countAdvicesOfType(Class adviceClass) { - Assert.notNull(adviceClass, "Advice class must not be null"); int count = 0; - for (int i = 0; i < this.advisors.size(); i++) { - Advisor advisor = (Advisor) this.advisors.get(i); - if (advisor.getAdvice() != null && - adviceClass.isAssignableFrom(advisor.getAdvice().getClass())) { - count++; + if (adviceClass != null) { + for (Advisor advisor : this.advisors) { + if (adviceClass.isInstance(advisor.getAdvice())) { + count++; + } } } return count; @@ -460,7 +456,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { */ public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) { MethodCacheKey cacheKey = new MethodCacheKey(method); - List cached = (List) this.methodCache.get(cacheKey); + List cached = this.methodCache.get(cacheKey); if (cached == null) { cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice( this, method, targetClass); @@ -484,7 +480,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @param other the AdvisedSupport object to copy configuration from */ protected void copyConfigurationFrom(AdvisedSupport other) { - copyConfigurationFrom(other, other.targetSource, new ArrayList(other.advisors)); + copyConfigurationFrom(other, other.targetSource, new ArrayList(other.advisors)); } /** @@ -494,13 +490,12 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @param targetSource the new TargetSource * @param advisors the Advisors for the chain */ - protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List advisors) { + protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List advisors) { copyFrom(other); this.targetSource = targetSource; this.advisorChainFactory = other.advisorChainFactory; - this.interfaces = new ArrayList(other.interfaces); - for (Iterator it = advisors.iterator(); it.hasNext();) { - Advisor advisor = (Advisor) it.next(); + this.interfaces = new ArrayList(other.interfaces); + for (Advisor advisor : advisors) { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } @@ -549,8 +544,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { */ @Override public String toString() { - StringBuffer sb = new StringBuffer(getClass().getName() + ": "); - sb.append(this.interfaces.size()).append(" interfaces "); + StringBuilder sb = new StringBuilder(getClass().getName()); + sb.append(": ").append(this.interfaces.size()).append(" interfaces "); sb.append(ClassUtils.classNamesToString(this.interfaces)).append("; "); sb.append(this.advisors.size()).append(" advisors "); sb.append(this.advisors).append("; "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java index fcaaf7d33e5..53bb3b19c55 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java @@ -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,6 +35,7 @@ public interface AdvisorChainFactory { * @param targetClass the target class * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers) */ - List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass); + List getInterceptorsAndDynamicInterceptionAdvice( + Advised config, Method method, Class targetClass); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java index 0d78453adff..54e73e13a12 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java @@ -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. @@ -19,7 +19,6 @@ package org.springframework.aop.framework; import java.util.Arrays; import org.springframework.aop.SpringProxy; -import org.springframework.aop.support.AopUtils; import org.springframework.util.Assert; /** @@ -35,27 +34,6 @@ import org.springframework.util.Assert; */ public abstract class AopProxyUtils { - /** - * Determine the target class of the given bean instance, - * which might be an AOP proxy. - * Returns the target class for an AOP proxy and the plain class else. - * @param candidate the instance to check (might be an AOP proxy) - * @return the target class (or the plain class of the given object as fallback) - * @deprecated as of Spring 2.0.3, in favor of AopUtils.getTargetClass - * @see org.springframework.aop.support.AopUtils#getTargetClass(Object) - */ - @Deprecated - public static Class getTargetClass(Object candidate) { - Assert.notNull(candidate, "Candidate object must not be null"); - if (AopUtils.isCglibProxy(candidate)) { - return candidate.getClass().getSuperclass(); - } - if (candidate instanceof Advised) { - return ((Advised) candidate).getTargetSource().getTargetClass(); - } - return candidate.getClass(); - } - /** * Determine the complete set of interfaces to proxy for the given AOP configuration. * This will always add the {@link Advised} interface unless the AdvisedSupport's diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java index 84c04967591..806e3602bc9 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java @@ -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,15 +45,15 @@ import org.springframework.aop.support.MethodMatchers; */ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable { - public List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass) { + public List getInterceptorsAndDynamicInterceptionAdvice( + Advised config, Method method, Class targetClass) { + // This is somewhat tricky... we have to process introductions first, // but we need to preserve order in the ultimate list. - List interceptorList = new ArrayList(config.getAdvisors().length); + List interceptorList = new ArrayList(config.getAdvisors().length); boolean hasIntroductions = hasMatchingIntroductions(config, targetClass); AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance(); - Advisor[] advisors = config.getAdvisors(); - for (int i = 0; i < advisors.length; i++) { - Advisor advisor = advisors[i]; + for (Advisor advisor : config.getAdvisors()) { if (advisor instanceof PointcutAdvisor) { // Add it conditionally. PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; @@ -64,8 +64,8 @@ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializ if (mm.isRuntime()) { // Creating a new object instance in the getInterceptors() method // isn't a problem as we normally cache created chains. - for (int j = 0; j < interceptors.length; j++) { - interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptors[j], mm)); + for (MethodInterceptor interceptor : interceptors) { + interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm)); } } else { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java index 905fb85a83f..a256e95c362 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java @@ -160,7 +160,7 @@ public class ProxyConfig implements Serializable { @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("proxyTargetClass=").append(this.proxyTargetClass).append("; "); sb.append("optimize=").append(this.optimize).append("; "); sb.append("opaque=").append(this.opaque).append("; "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java index 1290a301594..c487b512fa3 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java @@ -265,7 +265,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea @Override public String toString() { // Don't do toString on target, it may be proxied. - StringBuffer sb = new StringBuffer("ReflectiveMethodInvocation: "); + StringBuilder sb = new StringBuilder("ReflectiveMethodInvocation: "); sb.append(this.method).append("; "); if (this.target == null) { sb.append("target is null"); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java index 36b14384014..56262b29889 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java @@ -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. @@ -19,6 +19,7 @@ package org.springframework.aop.framework.autoproxy; import java.util.Collections; import java.util.List; +import org.springframework.aop.Advisor; import org.springframework.aop.TargetSource; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactory; @@ -82,9 +83,9 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @see #sortAdvisors * @see #extendAdvisors */ - protected List findEligibleAdvisors(Class beanClass, String beanName) { - List candidateAdvisors = findCandidateAdvisors(); - List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); + protected List findEligibleAdvisors(Class beanClass, String beanName) { + List candidateAdvisors = findCandidateAdvisors(); + List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); if (!eligibleAdvisors.isEmpty()) { eligibleAdvisors = sortAdvisors(eligibleAdvisors); } @@ -96,7 +97,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * Find all candidate Advisors to use in auto-proxying. * @return the List of candidate Advisors */ - protected List findCandidateAdvisors() { + protected List findCandidateAdvisors() { return this.advisorRetrievalHelper.findAdvisorBeans(); } @@ -109,7 +110,9 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @return the List of applicable Advisors * @see ProxyCreationContext#getCurrentProxiedBeanName() */ - protected List findAdvisorsThatCanApply(List candidateAdvisors, Class beanClass, String beanName) { + protected List findAdvisorsThatCanApply( + List candidateAdvisors, Class beanClass, String beanName) { + ProxyCreationContext.setCurrentProxiedBeanName(beanName); try { return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); @@ -137,7 +140,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @see org.springframework.core.Ordered * @see org.springframework.core.OrderComparator */ - protected List sortAdvisors(List advisors) { + protected List sortAdvisors(List advisors) { Collections.sort(advisors, new OrderComparator()); return advisors; } @@ -151,7 +154,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @param candidateAdvisors Advisors that have already been identified as * applying to a given bean */ - protected void extendAdvisors(List candidateAdvisors) { + protected void extendAdvisors(List candidateAdvisors) { } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java index 8376f97b5b9..d735500922a 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java @@ -25,6 +25,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.aopalliance.aop.Advice; import org.apache.commons.logging.Log; @@ -46,7 +47,6 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; -import org.springframework.core.CollectionFactory; import org.springframework.core.Ordered; import org.springframework.util.ClassUtils; @@ -136,20 +136,15 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig private BeanFactory beanFactory; - /** - * Set of bean name Strings, referring to all beans that this auto-proxy creator - * created a custom TargetSource for. Used to detect own pre-built proxies (from - * "postProcessBeforeInstantiation") in the "postProcessAfterInitialization" method. - */ - private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); + private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); - private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); + private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); - private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); + private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); - private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); + private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); - private final Map proxyTypes = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map proxyTypes = new ConcurrentHashMap(); /** @@ -260,7 +255,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig public Class predictBeanType(Class beanClass, String beanName) { Object cacheKey = getCacheKey(beanClass, beanName); - return (Class) this.proxyTypes.get(cacheKey); + return this.proxyTypes.get(cacheKey); } public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { @@ -280,7 +275,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig if (this.advisedBeans.contains(cacheKey) || this.nonAdvisedBeans.contains(cacheKey)) { return null; } - if (isInfrastructureClass(beanClass, beanName) || shouldSkip(beanClass, beanName)) { + if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { this.nonAdvisedBeans.add(cacheKey); return null; } @@ -355,7 +350,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig if (this.nonAdvisedBeans.contains(cacheKey)) { return bean; } - if (isInfrastructureClass(bean.getClass(), beanName) || shouldSkip(bean.getClass(), beanName)) { + if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.nonAdvisedBeans.add(cacheKey); return bean; } @@ -373,17 +368,6 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig return bean; } - /** - * Return whether the given bean class and bean name represents an - * infrastructure class that should never be proxied. - * @deprecated in favor of isInfrastructureClass(beanClass) - * @see #isInfrastructureClass(Class) - */ - @Deprecated - protected boolean isInfrastructureClass(Class beanClass, String beanName) { - return isInfrastructureClass(beanClass); - } - /** * Return whether the given bean class represents an infrastructure class * that should never be proxied. @@ -432,8 +416,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // We can't create fancy target sources for directly registered singletons. if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) { - for (int i = 0; i < this.customTargetSourceCreators.length; i++) { - TargetSourceCreator tsc = this.customTargetSourceCreators[i]; + for (TargetSourceCreator tsc : this.customTargetSourceCreators) { TargetSource ts = tsc.getTargetSource(beanClass, beanName); if (ts != null) { // Found a matching TargetSource. @@ -472,14 +455,14 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // Must allow for introductions; can't just set interfaces to // the target's interfaces only. Class[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader); - for (int i = 0; i < targetInterfaces.length; i++) { - proxyFactory.addInterface(targetInterfaces[i]); + for (Class targetInterface : targetInterfaces) { + proxyFactory.addInterface(targetInterface); } } Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); - for (int i = 0; i < advisors.length; i++) { - proxyFactory.addAdvisor(advisors[i]); + for (Advisor advisor : advisors) { + proxyFactory.addAdvisor(advisor); } proxyFactory.setTargetSource(targetSource); @@ -536,7 +519,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // Handle prototypes correctly... Advisor[] commonInterceptors = resolveInterceptorNames(); - List allInterceptors = new ArrayList(); + List allInterceptors = new ArrayList(); if (specificInterceptors != null) { allInterceptors.addAll(Arrays.asList(specificInterceptors)); if (commonInterceptors != null) { @@ -567,17 +550,16 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig * @see #setInterceptorNames */ private Advisor[] resolveInterceptorNames() { - ConfigurableBeanFactory cbf = - (this.beanFactory instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) this.beanFactory : null); - List advisors = new ArrayList(); - for (int i = 0; i < this.interceptorNames.length; i++) { - String beanName = this.interceptorNames[i]; + ConfigurableBeanFactory cbf = (this.beanFactory instanceof ConfigurableBeanFactory) ? + (ConfigurableBeanFactory) this.beanFactory : null; + List advisors = new ArrayList(); + for (String beanName : this.interceptorNames) { if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) { Object next = this.beanFactory.getBean(beanName); advisors.add(this.advisorAdapterRegistry.wrap(next)); } } - return (Advisor[]) advisors.toArray(new Advisor[advisors.size()]); + return advisors.toArray(new Advisor[advisors.size()]); } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java index 40ed9e85e71..49a964f1b27 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java @@ -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. @@ -79,12 +79,11 @@ public class BeanFactoryAdvisorRetrievalHelper { return new LinkedList(); } - List advisors = new LinkedList(); - for (int i = 0; i < advisorNames.length; i++) { - String name = advisorNames[i]; + List advisors = new LinkedList(); + for (String name : advisorNames) { if (isEligibleBean(name) && !this.beanFactory.isCurrentlyInCreation(name)) { try { - advisors.add(this.beanFactory.getBean(name)); + advisors.add(this.beanFactory.getBean(name, Advisor.class)); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java index 084c906f1d9..cec7f9907b1 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java @@ -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. @@ -17,7 +17,6 @@ package org.springframework.aop.framework.autoproxy; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.springframework.aop.TargetSource; @@ -45,7 +44,7 @@ import org.springframework.util.StringUtils; */ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { - private List beanNames; + private List beanNames; /** @@ -62,9 +61,9 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { */ public void setBeanNames(String[] beanNames) { Assert.notEmpty(beanNames, "'beanNames' must not be empty"); - this.beanNames = new ArrayList(beanNames.length); - for (int i = 0; i < beanNames.length; i++) { - this.beanNames.add(StringUtils.trimWhitespace(beanNames[i])); + this.beanNames = new ArrayList(beanNames.length); + for (String mappedName : beanNames) { + this.beanNames.add(StringUtils.trimWhitespace(mappedName)); } } @@ -75,8 +74,7 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { @Override protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { if (this.beanNames != null) { - for (Iterator it = this.beanNames.iterator(); it.hasNext();) { - String mappedName = (String) it.next(); + for (String mappedName : this.beanNames) { if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { continue; diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java index 3ce05a06811..0c257c1c506 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java @@ -95,7 +95,7 @@ public abstract class AbstractMonitoringInterceptor extends AbstractTraceInterce * @see #setSuffix */ protected String createInvocationTraceName(MethodInvocation invocation) { - StringBuffer sb = new StringBuffer(getPrefix()); + StringBuilder sb = new StringBuilder(getPrefix()); Method method = invocation.getMethod(); Class clazz = method.getDeclaringClass(); if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java index fa20d21a2d8..db00bcbbf6f 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java @@ -423,7 +423,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { * here for JDK 1.4 compliance reasons only. */ private String escape(String input) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '\\') { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java b/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java index 43cab6981ae..2f441102cbd 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java @@ -20,7 +20,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -35,7 +34,6 @@ import org.springframework.aop.PointcutAdvisor; import org.springframework.aop.SpringProxy; import org.springframework.aop.TargetClassAware; import org.springframework.core.BridgeMethodResolver; -import org.springframework.core.JdkVersion; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -88,7 +86,7 @@ public abstract class AopUtils { * @param clazz the class to check */ public static boolean isCglibProxyClass(Class clazz) { - return (clazz != null && clazz.getName().indexOf(ClassUtils.CGLIB_CLASS_SEPARATOR) != -1); + return (clazz != null && clazz.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)); } /** @@ -162,10 +160,7 @@ public abstract class AopUtils { public static Method getMostSpecificMethod(Method method, Class targetClass) { Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the original method. - if (JdkVersion.isAtLeastJava15()) { - resolvedMethod = BridgeMethodResolver.findBridgedMethod(resolvedMethod); - } - return resolvedMethod; + return BridgeMethodResolver.findBridgedMethod(resolvedMethod); } @@ -202,15 +197,14 @@ public abstract class AopUtils { introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; } - Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); + Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); classes.add(targetClass); - for (Iterator it = classes.iterator(); it.hasNext();) { - Class clazz = (Class) it.next(); + for (Class clazz : classes) { Method[] methods = clazz.getMethods(); - for (int j = 0; j < methods.length; j++) { + for (Method method : methods) { if ((introductionAwareMethodMatcher != null && - introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) || - methodMatcher.matches(methods[j], targetClass)) { + introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) || + methodMatcher.matches(method, targetClass)) { return true; } } @@ -263,20 +257,18 @@ public abstract class AopUtils { * @return sublist of Advisors that can apply to an object of the given class * (may be the incoming List as-is) */ - public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { + public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { if (candidateAdvisors.isEmpty()) { return candidateAdvisors; } - List eligibleAdvisors = new LinkedList(); - for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { - Advisor candidate = (Advisor) it.next(); + List eligibleAdvisors = new LinkedList(); + for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { eligibleAdvisors.add(candidate); } } boolean hasIntroductions = !eligibleAdvisors.isEmpty(); - for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { - Advisor candidate = (Advisor) it.next(); + for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor) { // already processed continue; diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java b/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java index fcd7bc862f7..f8a0e3a50d7 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java @@ -204,7 +204,7 @@ public abstract class AbstractBeanFactoryBasedTargetSource @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(ClassUtils.getShortName(getClass())); sb.append(" for target bean '").append(this.targetBeanName).append("'"); if (this.targetClass != null) { diff --git a/org.springframework.beans/beans.iml b/org.springframework.beans/beans.iml index 595f99187d4..733bb27def4 100644 --- a/org.springframework.beans/beans.iml +++ b/org.springframework.beans/beans.iml @@ -1,99 +1,99 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java index 40942327957..2df53e11b02 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java @@ -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 propertyAccessExceptions = null; + List 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(); } 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java index d41cb645aa1..1c69257f064 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java @@ -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 unknownEditorTypes = + Collections.synchronizedMap(new WeakHashMap()); /** @@ -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 null 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 ClassUtils.isAssignable - * @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 ClassUtils.isAssignableValue - * @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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java index 3a294a66c38..3e18122ba74 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java @@ -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 null if none set diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java index c596c8ed159..1b4251b7f91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java @@ -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 convertIfNecessary - * @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("]"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java b/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java index dcbbb3af6ae..64f5e776441 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java @@ -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 acceptedClassLoaders = Collections.synchronizedSet(new HashSet()); /** * 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 classCache = Collections.synchronizedMap(new WeakHashMap()); /** @@ -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(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 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(); // 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java b/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java index 8396a72a841..33c14976c2f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java @@ -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 propertyValueList; - private Set processedProperties; + private Set 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(); } /** @@ -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(pvs.length); + for (PropertyValue pv : pvs) { + this.propertyValueList.add(new PropertyValue(pv)); } } else { - this.propertyValueList = new ArrayList(0); + this.propertyValueList = new ArrayList(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(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(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 propertyValueList) { + this.propertyValueList = + (propertyValueList != null ? propertyValueList : new ArrayList()); } @@ -119,7 +115,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { * This is an accessor for optimized access to all PropertyValue objects. * It is not intended for typical programmatic use. */ - public List getPropertyValueList() { + public List 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(); } 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java index 3e5717e25ec..a433ec959d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java @@ -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(); } /** diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java index 0dff5620ec9..f15ba5a45a6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java @@ -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++) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java index 1bda68f1956..688f5dff9d6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java index 7d81091cd70..8f3c96e138e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java index b08692e472e..486f9248e7d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java @@ -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 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(); } 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java new file mode 100644 index 00000000000..ab2f2531b0d --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java @@ -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); + } + +} \ No newline at end of file diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java index 98e4441121a..c31a4c8338e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java @@ -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 getBean(String name, Class requiredType) throws BeansException; /** * Return an instance, which may be shared or independent, of the specified bean. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java index 501b52fab40..f2b4cbd4583 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java @@ -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 resultList = new ArrayList(); 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 resultList = new ArrayList(); 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 Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(4); result.putAll(lbf.getBeansOfType(type)); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { - Map parentResult = beansOfTypeIncludingAncestors( + Map 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 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 Map beansOfTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(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 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 entry : parentResult.entrySet()) { + String beanName = entry.getKey(); if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { result.put(beanName, entry.getValue()); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java index 8a0472f2bec..4b8247f3689 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java @@ -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 { /** * 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 null 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, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java index fe3f909dcd9..c351f20cdc3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java @@ -172,7 +172,7 @@ $ * Does not consider any hierarchy this factory may participate in. * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) */ - Map getBeansOfType(Class type) throws BeansException; + Map getBeansOfType(Class type) throws BeansException; /** * Return the bean instances that match the given object type (including @@ -207,7 +207,7 @@ $ * 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) + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java index a84d222c0f0..b81ee6ca378 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java @@ -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 { /** * Return an instance (possibly shared or independent) @@ -43,6 +43,6 @@ public interface ObjectFactory { * @return an instance of the bean (should never be null) * @throws BeansException in case of creation errors */ - Object getObject() throws BeansException; + T getObject() throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java index f429b76acdb..c54676eda1e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java @@ -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 extends FactoryBean { /** * Is the object managed by this factory a prototype? That is, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 4d71b43b409..5832b90cdb5 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -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 candidates = new ArrayList(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 Map findAutowireCandidates(Class 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 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java index ec44c70812a..cc1584c8438 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java @@ -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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java index 289db5b6427..f4497ad316e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java @@ -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)) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java new file mode 100644 index 00000000000..beaba9be815 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java @@ -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(); + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java index 52c5fabe12a..15138353376 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java @@ -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 true (a singleton). + * Set if a singleton should be created, or a new object on each request + * otherwise. Default is true (a singleton). */ public void setSingleton(boolean singleton) { this.singleton = singleton; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java index 07f26595ecd..24fd58f233a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java @@ -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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java index 0176a914253..337bb9b93d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java index 18e7380ae25..0b16a0557e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java new file mode 100644 index 00000000000..d6111964a25 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java @@ -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); + } + } + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java new file mode 100644 index 00000000000..589417d1a03 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java @@ -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. + * + * 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; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java @@ -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, 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + * 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. * 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. - * 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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
Returns the target class for an AOP proxy and the plain class else. - * @param candidate the instance to check (might be an AOP proxy) - * @return the target class (or the plain class of the given object as fallback) - * @deprecated as of Spring 2.0.3, in favor of AopUtils.getTargetClass - * @see org.springframework.aop.support.AopUtils#getTargetClass(Object) - */ - @Deprecated - public static Class getTargetClass(Object candidate) { - Assert.notNull(candidate, "Candidate object must not be null"); - if (AopUtils.isCglibProxy(candidate)) { - return candidate.getClass().getSuperclass(); - } - if (candidate instanceof Advised) { - return ((Advised) candidate).getTargetSource().getTargetClass(); - } - return candidate.getClass(); - } - /** * Determine the complete set of interfaces to proxy for the given AOP configuration. *
AopUtils.getTargetClass
This will always add the {@link Advised} interface unless the AdvisedSupport's diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java index 84c04967591..806e3602bc9 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java @@ -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,15 +45,15 @@ import org.springframework.aop.support.MethodMatchers; */ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable { - public List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass) { + public List getInterceptorsAndDynamicInterceptionAdvice( + Advised config, Method method, Class targetClass) { + // This is somewhat tricky... we have to process introductions first, // but we need to preserve order in the ultimate list. - List interceptorList = new ArrayList(config.getAdvisors().length); + List interceptorList = new ArrayList(config.getAdvisors().length); boolean hasIntroductions = hasMatchingIntroductions(config, targetClass); AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance(); - Advisor[] advisors = config.getAdvisors(); - for (int i = 0; i < advisors.length; i++) { - Advisor advisor = advisors[i]; + for (Advisor advisor : config.getAdvisors()) { if (advisor instanceof PointcutAdvisor) { // Add it conditionally. PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; @@ -64,8 +64,8 @@ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializ if (mm.isRuntime()) { // Creating a new object instance in the getInterceptors() method // isn't a problem as we normally cache created chains. - for (int j = 0; j < interceptors.length; j++) { - interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptors[j], mm)); + for (MethodInterceptor interceptor : interceptors) { + interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm)); } } else { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java index 905fb85a83f..a256e95c362 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java @@ -160,7 +160,7 @@ public class ProxyConfig implements Serializable { @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("proxyTargetClass=").append(this.proxyTargetClass).append("; "); sb.append("optimize=").append(this.optimize).append("; "); sb.append("opaque=").append(this.opaque).append("; "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java index 1290a301594..c487b512fa3 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java @@ -265,7 +265,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea @Override public String toString() { // Don't do toString on target, it may be proxied. - StringBuffer sb = new StringBuffer("ReflectiveMethodInvocation: "); + StringBuilder sb = new StringBuilder("ReflectiveMethodInvocation: "); sb.append(this.method).append("; "); if (this.target == null) { sb.append("target is null"); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java index 36b14384014..56262b29889 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java @@ -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. @@ -19,6 +19,7 @@ package org.springframework.aop.framework.autoproxy; import java.util.Collections; import java.util.List; +import org.springframework.aop.Advisor; import org.springframework.aop.TargetSource; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactory; @@ -82,9 +83,9 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @see #sortAdvisors * @see #extendAdvisors */ - protected List findEligibleAdvisors(Class beanClass, String beanName) { - List candidateAdvisors = findCandidateAdvisors(); - List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); + protected List findEligibleAdvisors(Class beanClass, String beanName) { + List candidateAdvisors = findCandidateAdvisors(); + List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); if (!eligibleAdvisors.isEmpty()) { eligibleAdvisors = sortAdvisors(eligibleAdvisors); } @@ -96,7 +97,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * Find all candidate Advisors to use in auto-proxying. * @return the List of candidate Advisors */ - protected List findCandidateAdvisors() { + protected List findCandidateAdvisors() { return this.advisorRetrievalHelper.findAdvisorBeans(); } @@ -109,7 +110,9 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @return the List of applicable Advisors * @see ProxyCreationContext#getCurrentProxiedBeanName() */ - protected List findAdvisorsThatCanApply(List candidateAdvisors, Class beanClass, String beanName) { + protected List findAdvisorsThatCanApply( + List candidateAdvisors, Class beanClass, String beanName) { + ProxyCreationContext.setCurrentProxiedBeanName(beanName); try { return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); @@ -137,7 +140,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @see org.springframework.core.Ordered * @see org.springframework.core.OrderComparator */ - protected List sortAdvisors(List advisors) { + protected List sortAdvisors(List advisors) { Collections.sort(advisors, new OrderComparator()); return advisors; } @@ -151,7 +154,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @param candidateAdvisors Advisors that have already been identified as * applying to a given bean */ - protected void extendAdvisors(List candidateAdvisors) { + protected void extendAdvisors(List candidateAdvisors) { } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java index 8376f97b5b9..d735500922a 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java @@ -25,6 +25,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.aopalliance.aop.Advice; import org.apache.commons.logging.Log; @@ -46,7 +47,6 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; -import org.springframework.core.CollectionFactory; import org.springframework.core.Ordered; import org.springframework.util.ClassUtils; @@ -136,20 +136,15 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig private BeanFactory beanFactory; - /** - * Set of bean name Strings, referring to all beans that this auto-proxy creator - * created a custom TargetSource for. Used to detect own pre-built proxies (from - * "postProcessBeforeInstantiation") in the "postProcessAfterInitialization" method. - */ - private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); + private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); - private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); + private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); - private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); + private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); - private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); + private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); - private final Map proxyTypes = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map proxyTypes = new ConcurrentHashMap(); /** @@ -260,7 +255,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig public Class predictBeanType(Class beanClass, String beanName) { Object cacheKey = getCacheKey(beanClass, beanName); - return (Class) this.proxyTypes.get(cacheKey); + return this.proxyTypes.get(cacheKey); } public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { @@ -280,7 +275,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig if (this.advisedBeans.contains(cacheKey) || this.nonAdvisedBeans.contains(cacheKey)) { return null; } - if (isInfrastructureClass(beanClass, beanName) || shouldSkip(beanClass, beanName)) { + if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { this.nonAdvisedBeans.add(cacheKey); return null; } @@ -355,7 +350,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig if (this.nonAdvisedBeans.contains(cacheKey)) { return bean; } - if (isInfrastructureClass(bean.getClass(), beanName) || shouldSkip(bean.getClass(), beanName)) { + if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.nonAdvisedBeans.add(cacheKey); return bean; } @@ -373,17 +368,6 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig return bean; } - /** - * Return whether the given bean class and bean name represents an - * infrastructure class that should never be proxied. - * @deprecated in favor of isInfrastructureClass(beanClass) - * @see #isInfrastructureClass(Class) - */ - @Deprecated - protected boolean isInfrastructureClass(Class beanClass, String beanName) { - return isInfrastructureClass(beanClass); - } - /** * Return whether the given bean class represents an infrastructure class * that should never be proxied. @@ -432,8 +416,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // We can't create fancy target sources for directly registered singletons. if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) { - for (int i = 0; i < this.customTargetSourceCreators.length; i++) { - TargetSourceCreator tsc = this.customTargetSourceCreators[i]; + for (TargetSourceCreator tsc : this.customTargetSourceCreators) { TargetSource ts = tsc.getTargetSource(beanClass, beanName); if (ts != null) { // Found a matching TargetSource. @@ -472,14 +455,14 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // Must allow for introductions; can't just set interfaces to // the target's interfaces only. Class[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader); - for (int i = 0; i < targetInterfaces.length; i++) { - proxyFactory.addInterface(targetInterfaces[i]); + for (Class targetInterface : targetInterfaces) { + proxyFactory.addInterface(targetInterface); } } Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); - for (int i = 0; i < advisors.length; i++) { - proxyFactory.addAdvisor(advisors[i]); + for (Advisor advisor : advisors) { + proxyFactory.addAdvisor(advisor); } proxyFactory.setTargetSource(targetSource); @@ -536,7 +519,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // Handle prototypes correctly... Advisor[] commonInterceptors = resolveInterceptorNames(); - List allInterceptors = new ArrayList(); + List allInterceptors = new ArrayList(); if (specificInterceptors != null) { allInterceptors.addAll(Arrays.asList(specificInterceptors)); if (commonInterceptors != null) { @@ -567,17 +550,16 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig * @see #setInterceptorNames */ private Advisor[] resolveInterceptorNames() { - ConfigurableBeanFactory cbf = - (this.beanFactory instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) this.beanFactory : null); - List advisors = new ArrayList(); - for (int i = 0; i < this.interceptorNames.length; i++) { - String beanName = this.interceptorNames[i]; + ConfigurableBeanFactory cbf = (this.beanFactory instanceof ConfigurableBeanFactory) ? + (ConfigurableBeanFactory) this.beanFactory : null; + List advisors = new ArrayList(); + for (String beanName : this.interceptorNames) { if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) { Object next = this.beanFactory.getBean(beanName); advisors.add(this.advisorAdapterRegistry.wrap(next)); } } - return (Advisor[]) advisors.toArray(new Advisor[advisors.size()]); + return advisors.toArray(new Advisor[advisors.size()]); } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java index 40ed9e85e71..49a964f1b27 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java @@ -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. @@ -79,12 +79,11 @@ public class BeanFactoryAdvisorRetrievalHelper { return new LinkedList(); } - List advisors = new LinkedList(); - for (int i = 0; i < advisorNames.length; i++) { - String name = advisorNames[i]; + List advisors = new LinkedList(); + for (String name : advisorNames) { if (isEligibleBean(name) && !this.beanFactory.isCurrentlyInCreation(name)) { try { - advisors.add(this.beanFactory.getBean(name)); + advisors.add(this.beanFactory.getBean(name, Advisor.class)); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java index 084c906f1d9..cec7f9907b1 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java @@ -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. @@ -17,7 +17,6 @@ package org.springframework.aop.framework.autoproxy; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.springframework.aop.TargetSource; @@ -45,7 +44,7 @@ import org.springframework.util.StringUtils; */ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { - private List beanNames; + private List beanNames; /** @@ -62,9 +61,9 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { */ public void setBeanNames(String[] beanNames) { Assert.notEmpty(beanNames, "'beanNames' must not be empty"); - this.beanNames = new ArrayList(beanNames.length); - for (int i = 0; i < beanNames.length; i++) { - this.beanNames.add(StringUtils.trimWhitespace(beanNames[i])); + this.beanNames = new ArrayList(beanNames.length); + for (String mappedName : beanNames) { + this.beanNames.add(StringUtils.trimWhitespace(mappedName)); } } @@ -75,8 +74,7 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { @Override protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { if (this.beanNames != null) { - for (Iterator it = this.beanNames.iterator(); it.hasNext();) { - String mappedName = (String) it.next(); + for (String mappedName : this.beanNames) { if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { continue; diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java index 3ce05a06811..0c257c1c506 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java @@ -95,7 +95,7 @@ public abstract class AbstractMonitoringInterceptor extends AbstractTraceInterce * @see #setSuffix */ protected String createInvocationTraceName(MethodInvocation invocation) { - StringBuffer sb = new StringBuffer(getPrefix()); + StringBuilder sb = new StringBuilder(getPrefix()); Method method = invocation.getMethod(); Class clazz = method.getDeclaringClass(); if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java index fa20d21a2d8..db00bcbbf6f 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java @@ -423,7 +423,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { * here for JDK 1.4 compliance reasons only. */ private String escape(String input) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '\\') { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java b/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java index 43cab6981ae..2f441102cbd 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java @@ -20,7 +20,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -35,7 +34,6 @@ import org.springframework.aop.PointcutAdvisor; import org.springframework.aop.SpringProxy; import org.springframework.aop.TargetClassAware; import org.springframework.core.BridgeMethodResolver; -import org.springframework.core.JdkVersion; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -88,7 +86,7 @@ public abstract class AopUtils { * @param clazz the class to check */ public static boolean isCglibProxyClass(Class clazz) { - return (clazz != null && clazz.getName().indexOf(ClassUtils.CGLIB_CLASS_SEPARATOR) != -1); + return (clazz != null && clazz.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)); } /** @@ -162,10 +160,7 @@ public abstract class AopUtils { public static Method getMostSpecificMethod(Method method, Class targetClass) { Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the original method. - if (JdkVersion.isAtLeastJava15()) { - resolvedMethod = BridgeMethodResolver.findBridgedMethod(resolvedMethod); - } - return resolvedMethod; + return BridgeMethodResolver.findBridgedMethod(resolvedMethod); } @@ -202,15 +197,14 @@ public abstract class AopUtils { introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; } - Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); + Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); classes.add(targetClass); - for (Iterator it = classes.iterator(); it.hasNext();) { - Class clazz = (Class) it.next(); + for (Class clazz : classes) { Method[] methods = clazz.getMethods(); - for (int j = 0; j < methods.length; j++) { + for (Method method : methods) { if ((introductionAwareMethodMatcher != null && - introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) || - methodMatcher.matches(methods[j], targetClass)) { + introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) || + methodMatcher.matches(method, targetClass)) { return true; } } @@ -263,20 +257,18 @@ public abstract class AopUtils { * @return sublist of Advisors that can apply to an object of the given class * (may be the incoming List as-is) */ - public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { + public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { if (candidateAdvisors.isEmpty()) { return candidateAdvisors; } - List eligibleAdvisors = new LinkedList(); - for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { - Advisor candidate = (Advisor) it.next(); + List eligibleAdvisors = new LinkedList(); + for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { eligibleAdvisors.add(candidate); } } boolean hasIntroductions = !eligibleAdvisors.isEmpty(); - for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { - Advisor candidate = (Advisor) it.next(); + for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor) { // already processed continue; diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java b/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java index fcd7bc862f7..f8a0e3a50d7 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java @@ -204,7 +204,7 @@ public abstract class AbstractBeanFactoryBasedTargetSource @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(ClassUtils.getShortName(getClass())); sb.append(" for target bean '").append(this.targetBeanName).append("'"); if (this.targetClass != null) { diff --git a/org.springframework.beans/beans.iml b/org.springframework.beans/beans.iml index 595f99187d4..733bb27def4 100644 --- a/org.springframework.beans/beans.iml +++ b/org.springframework.beans/beans.iml @@ -1,99 +1,99 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java index 40942327957..2df53e11b02 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java @@ -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 propertyAccessExceptions = null; + List 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(); } 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java index d41cb645aa1..1c69257f064 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java @@ -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 unknownEditorTypes = + Collections.synchronizedMap(new WeakHashMap()); /** @@ -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 null 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 ClassUtils.isAssignable - * @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 ClassUtils.isAssignableValue - * @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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java index 3a294a66c38..3e18122ba74 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java @@ -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 null if none set diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java index c596c8ed159..1b4251b7f91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java @@ -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 convertIfNecessary - * @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("]"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java b/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java index dcbbb3af6ae..64f5e776441 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java @@ -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 acceptedClassLoaders = Collections.synchronizedSet(new HashSet()); /** * 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 classCache = Collections.synchronizedMap(new WeakHashMap()); /** @@ -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(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 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(); // 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java b/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java index 8396a72a841..33c14976c2f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java @@ -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 propertyValueList; - private Set processedProperties; + private Set 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(); } /** @@ -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(pvs.length); + for (PropertyValue pv : pvs) { + this.propertyValueList.add(new PropertyValue(pv)); } } else { - this.propertyValueList = new ArrayList(0); + this.propertyValueList = new ArrayList(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(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(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 propertyValueList) { + this.propertyValueList = + (propertyValueList != null ? propertyValueList : new ArrayList()); } @@ -119,7 +115,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { * This is an accessor for optimized access to all PropertyValue objects. * It is not intended for typical programmatic use. */ - public List getPropertyValueList() { + public List 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(); } 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java index 3e5717e25ec..a433ec959d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java @@ -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(); } /** diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java index 0dff5620ec9..f15ba5a45a6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java @@ -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++) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java index 1bda68f1956..688f5dff9d6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java index 7d81091cd70..8f3c96e138e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java index b08692e472e..486f9248e7d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java @@ -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 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(); } 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java new file mode 100644 index 00000000000..ab2f2531b0d --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java @@ -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); + } + +} \ No newline at end of file diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java index 98e4441121a..c31a4c8338e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java @@ -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 getBean(String name, Class requiredType) throws BeansException; /** * Return an instance, which may be shared or independent, of the specified bean. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java index 501b52fab40..f2b4cbd4583 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java @@ -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 resultList = new ArrayList(); 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 resultList = new ArrayList(); 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 Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(4); result.putAll(lbf.getBeansOfType(type)); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { - Map parentResult = beansOfTypeIncludingAncestors( + Map 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 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 Map beansOfTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(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 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 entry : parentResult.entrySet()) { + String beanName = entry.getKey(); if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { result.put(beanName, entry.getValue()); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java index 8a0472f2bec..4b8247f3689 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java @@ -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 { /** * 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 null 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, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java index fe3f909dcd9..c351f20cdc3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java @@ -172,7 +172,7 @@ $ * Does not consider any hierarchy this factory may participate in. * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) */ - Map getBeansOfType(Class type) throws BeansException; + Map getBeansOfType(Class type) throws BeansException; /** * Return the bean instances that match the given object type (including @@ -207,7 +207,7 @@ $ * 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) + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java index a84d222c0f0..b81ee6ca378 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java @@ -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 { /** * Return an instance (possibly shared or independent) @@ -43,6 +43,6 @@ public interface ObjectFactory { * @return an instance of the bean (should never be null) * @throws BeansException in case of creation errors */ - Object getObject() throws BeansException; + T getObject() throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java index f429b76acdb..c54676eda1e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java @@ -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 extends FactoryBean { /** * Is the object managed by this factory a prototype? That is, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 4d71b43b409..5832b90cdb5 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -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 candidates = new ArrayList(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 Map findAutowireCandidates(Class 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 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java index ec44c70812a..cc1584c8438 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java @@ -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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java index 289db5b6427..f4497ad316e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java @@ -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)) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java new file mode 100644 index 00000000000..beaba9be815 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java @@ -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(); + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java index 52c5fabe12a..15138353376 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java @@ -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 true (a singleton). + * Set if a singleton should be created, or a new object on each request + * otherwise. Default is true (a singleton). */ public void setSingleton(boolean singleton) { this.singleton = singleton; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java index 07f26595ecd..24fd58f233a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java @@ -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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java index 0176a914253..337bb9b93d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java index 18e7380ae25..0b16a0557e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java new file mode 100644 index 00000000000..d6111964a25 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java @@ -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); + } + } + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java new file mode 100644 index 00000000000..589417d1a03 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java @@ -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. + * + * 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; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java @@ -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, 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + * 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. * 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. - * 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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
isInfrastructureClass(beanClass)
null
ClassUtils.isAssignable
ClassUtils.isAssignableValue
convertIfNecessary
This is an accessor for optimized access to all PropertyValue objects. * It is not intended for typical programmatic use. */ - public List getPropertyValueList() { + public List 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(); } 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java index 3e5717e25ec..a433ec959d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java @@ -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(); } /** diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java index 0dff5620ec9..f15ba5a45a6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java @@ -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++) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java index 1bda68f1956..688f5dff9d6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java index 7d81091cd70..8f3c96e138e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java index b08692e472e..486f9248e7d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java @@ -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 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(); } 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java new file mode 100644 index 00000000000..ab2f2531b0d --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java @@ -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); + } + +} \ No newline at end of file diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java index 98e4441121a..c31a4c8338e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java @@ -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 getBean(String name, Class requiredType) throws BeansException; /** * Return an instance, which may be shared or independent, of the specified bean. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java index 501b52fab40..f2b4cbd4583 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java @@ -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 resultList = new ArrayList(); 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 resultList = new ArrayList(); 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 Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(4); result.putAll(lbf.getBeansOfType(type)); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { - Map parentResult = beansOfTypeIncludingAncestors( + Map 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 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 Map beansOfTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(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 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 entry : parentResult.entrySet()) { + String beanName = entry.getKey(); if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { result.put(beanName, entry.getValue()); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java index 8a0472f2bec..4b8247f3689 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java @@ -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 { /** * 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 null 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, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java index fe3f909dcd9..c351f20cdc3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java @@ -172,7 +172,7 @@ $ * Does not consider any hierarchy this factory may participate in. * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) */ - Map getBeansOfType(Class type) throws BeansException; + Map getBeansOfType(Class type) throws BeansException; /** * Return the bean instances that match the given object type (including @@ -207,7 +207,7 @@ $ * 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) + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java index a84d222c0f0..b81ee6ca378 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java @@ -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 { /** * Return an instance (possibly shared or independent) @@ -43,6 +43,6 @@ public interface ObjectFactory { * @return an instance of the bean (should never be null) * @throws BeansException in case of creation errors */ - Object getObject() throws BeansException; + T getObject() throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java index f429b76acdb..c54676eda1e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java @@ -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 extends FactoryBean { /** * Is the object managed by this factory a prototype? That is, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 4d71b43b409..5832b90cdb5 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -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 candidates = new ArrayList(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 Map findAutowireCandidates(Class 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 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java index ec44c70812a..cc1584c8438 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java @@ -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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java index 289db5b6427..f4497ad316e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java @@ -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)) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java new file mode 100644 index 00000000000..beaba9be815 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java @@ -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(); + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java index 52c5fabe12a..15138353376 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java @@ -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 true (a singleton). + * Set if a singleton should be created, or a new object on each request + * otherwise. Default is true (a singleton). */ public void setSingleton(boolean singleton) { this.singleton = singleton; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java index 07f26595ecd..24fd58f233a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java @@ -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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java index 0176a914253..337bb9b93d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java index 18e7380ae25..0b16a0557e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java new file mode 100644 index 00000000000..d6111964a25 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java @@ -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); + } + } + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java new file mode 100644 index 00000000000..589417d1a03 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java @@ -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. + * + * 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; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java @@ -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, 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + * 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. * 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. - * 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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
Does not consider any hierarchy this factory may participate in. * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) */ - Map getBeansOfType(Class type) throws BeansException; + Map getBeansOfType(Class type) throws BeansException; /** * Return the bean instances that match the given object type (including @@ -207,7 +207,7 @@ $ * 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) + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java index a84d222c0f0..b81ee6ca378 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java @@ -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 { /** * Return an instance (possibly shared or independent) @@ -43,6 +43,6 @@ public interface ObjectFactory { * @return an instance of the bean (should never be null) * @throws BeansException in case of creation errors */ - Object getObject() throws BeansException; + T getObject() throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java index f429b76acdb..c54676eda1e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java @@ -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 extends FactoryBean { /** * Is the object managed by this factory a prototype? That is, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 4d71b43b409..5832b90cdb5 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -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 candidates = new ArrayList(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 Map findAutowireCandidates(Class 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 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java index ec44c70812a..cc1584c8438 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java @@ -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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java index 289db5b6427..f4497ad316e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java @@ -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)) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java new file mode 100644 index 00000000000..beaba9be815 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java @@ -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(); + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java index 52c5fabe12a..15138353376 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java @@ -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 true (a singleton). + * Set if a singleton should be created, or a new object on each request + * otherwise. Default is true (a singleton). */ public void setSingleton(boolean singleton) { this.singleton = singleton; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java index 07f26595ecd..24fd58f233a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java @@ -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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java index 0176a914253..337bb9b93d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java index 18e7380ae25..0b16a0557e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java new file mode 100644 index 00000000000..d6111964a25 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java @@ -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); + } + } + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java new file mode 100644 index 00000000000..589417d1a03 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java @@ -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. + * + * 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; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java @@ -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, 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + * 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. * 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. - * 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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
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) + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java index a84d222c0f0..b81ee6ca378 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java @@ -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 { /** * Return an instance (possibly shared or independent) @@ -43,6 +43,6 @@ public interface ObjectFactory { * @return an instance of the bean (should never be null) * @throws BeansException in case of creation errors */ - Object getObject() throws BeansException; + T getObject() throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java index f429b76acdb..c54676eda1e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java @@ -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 extends FactoryBean { /** * Is the object managed by this factory a prototype? That is, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 4d71b43b409..5832b90cdb5 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -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 candidates = new ArrayList(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 Map findAutowireCandidates(Class 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 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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java index ec44c70812a..cc1584c8438 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java @@ -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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java index 289db5b6427..f4497ad316e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java @@ -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)) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java new file mode 100644 index 00000000000..beaba9be815 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java @@ -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(); + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java index 52c5fabe12a..15138353376 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java @@ -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 true (a singleton). + * Set if a singleton should be created, or a new object on each request + * otherwise. Default is true (a singleton). */ public void setSingleton(boolean singleton) { this.singleton = singleton; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java index 07f26595ecd..24fd58f233a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java @@ -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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java index 0176a914253..337bb9b93d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java index 18e7380ae25..0b16a0557e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java new file mode 100644 index 00000000000..d6111964a25 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java @@ -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); + } + } + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java new file mode 100644 index 00000000000..589417d1a03 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java @@ -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. + * + * 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; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java @@ -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, 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + * 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. * 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. - * 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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
true
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; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java @@ -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, 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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + * 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. * 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. - * 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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
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. *
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. - *
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 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 + * 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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -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 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. - * 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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
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 Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map 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 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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -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 null 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 null 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 null 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 null 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 Annotation[] 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 { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 88a72972094..6d40aba2d69 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index 8a6ece50a64..a20f29120dc 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -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 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()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java @@ -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 null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. * The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
Map
Annotation[]
The exact meaning of the conversation ID depends on the underlying diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index fa643842815..4b62b57fa5d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -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) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java @@ -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'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -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()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -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 ignoredDependencyTypes = new HashSet(); /** * 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 ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -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() { 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 actualDependentBeans = new LinkedHashSet(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 returnTypes = new HashSet(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 autowiredBeanNames = new LinkedHashSet(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 result = new TreeSet(); 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 pds = + new LinkedList(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 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 deepCopy = new ArrayList(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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -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); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index a4e366f4313..f8181f6ade9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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 propertyEditorRegistrars = + new LinkedHashSet(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> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** 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 scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("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 getBean(String name, Class 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 getBean(String name, Class 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 doGetBean( + final String name, final Class 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 aliases = new ArrayList(); 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 getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class 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> 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 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 beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) 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 beanNameSet = (Set) 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> 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() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -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() { + 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 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(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java @@ -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. - * 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. * The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
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. *
The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java @@ -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 null 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 createBeanDefinition(String, String, ClassLoader) - * @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. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -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; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -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); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index fefb9b1a2f0..2457d1525b1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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 beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** 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 resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // 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 Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class 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 result = new LinkedHashMap(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 autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map 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 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 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 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 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 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 result = new LinkedHashMap(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 null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map 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 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(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -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 singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set 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 disposableBeans = new LinkedHashMap(); /** 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> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** 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> dependenciesForBeanMap = new ConcurrentHashMap>(); 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(); } 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 containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(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 dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(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 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 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 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 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); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -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 factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -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() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java @@ -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 extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java @@ -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 extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java @@ -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 extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -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 owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -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 map = new HashMap
createBeanDefinition(String, String, ClassLoader)
owner.class=com.myapp.MyClass
owner.(parent)=parentBeanName