KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > beans > factory > support > ConstructorResolver


1 /*
2  * Copyright 2002-2007 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.beans.factory.support;
18
19 import java.lang.reflect.Constructor JavaDoc;
20 import java.lang.reflect.Method JavaDoc;
21 import java.lang.reflect.Modifier JavaDoc;
22 import java.util.HashSet JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import org.springframework.beans.BeanWrapper;
28 import org.springframework.beans.BeanWrapperImpl;
29 import org.springframework.beans.BeansException;
30 import org.springframework.beans.TypeMismatchException;
31 import org.springframework.beans.factory.BeanCreationException;
32 import org.springframework.beans.factory.BeanDefinitionStoreException;
33 import org.springframework.beans.factory.UnsatisfiedDependencyException;
34 import org.springframework.beans.factory.config.ConstructorArgumentValues;
35 import org.springframework.core.MethodParameter;
36 import org.springframework.util.ObjectUtils;
37 import org.springframework.util.ReflectionUtils;
38
39 /**
40  * Helper class for resolving constructors and factory methods.
41  * Performs constructor resolution through argument matching.
42  *
43  * <p>Works on an AbstractBeanFactory and an InstantiationStrategy.
44  * Used by AbstractAutowireCapableBeanFactory.
45  *
46  * @author Juergen Hoeller
47  * @since 2.0
48  * @see #autowireConstructor
49  * @see #instantiateUsingFactoryMethod
50  * @see AbstractAutowireCapableBeanFactory
51  */

52 abstract class ConstructorResolver {
53
54     private final AbstractBeanFactory beanFactory;
55
56     private final InstantiationStrategy instantiationStrategy;
57
58
59     /**
60      * Create a new ConstructorResolver for the given factory and instantiation strategy.
61      * @param beanFactory the BeanFactory to work with
62      * @param instantiationStrategy the instantiate strategy for creating bean instances
63      */

64     public ConstructorResolver(AbstractBeanFactory beanFactory, InstantiationStrategy instantiationStrategy) {
65         this.beanFactory = beanFactory;
66         this.instantiationStrategy = instantiationStrategy;
67     }
68
69
70     /**
71      * "autowire constructor" (with constructor arguments by type) behavior.
72      * Also applied if explicit constructor argument values are specified,
73      * matching all remaining arguments with beans from the bean factory.
74      * <p>This corresponds to constructor injection: In this mode, a Spring
75      * bean factory is able to host components that expect constructor-based
76      * dependency resolution.
77      * @param beanName the name of the bean
78      * @param mbd the merged bean definition for the bean
79      * @return a BeanWrapper for the new instance
80      */

81     protected BeanWrapper autowireConstructor(String JavaDoc beanName, RootBeanDefinition mbd) {
82         ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
83         ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
84
85         BeanWrapper bw = new BeanWrapperImpl();
86         this.beanFactory.initBeanWrapper(bw);
87
88         int minNrOfArgs = 0;
89         if (cargs != null) {
90             minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
91         }
92
93         Constructor JavaDoc[] candidates = mbd.getBeanClass().getDeclaredConstructors();
94         AutowireUtils.sortConstructors(candidates);
95
96         Constructor JavaDoc constructorToUse = null;
97         Object JavaDoc[] argsToUse = null;
98         int minTypeDiffWeight = Integer.MAX_VALUE;
99
100         for (int i = 0; i < candidates.length; i++) {
101             Constructor JavaDoc constructor = candidates[i];
102
103             if (constructorToUse != null &&
104                     constructorToUse.getParameterTypes().length > constructor.getParameterTypes().length) {
105                 // Already found greedy constructor that can be satisfied ->
106
// do not look any further, there are only less greedy constructors left.
107
break;
108             }
109             if (constructor.getParameterTypes().length < minNrOfArgs) {
110                 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
111                         minNrOfArgs + " constructor arguments specified but no matching constructor found in bean '" +
112                         beanName + "' " +
113                         "(hint: specify index and/or type arguments for simple parameters to avoid type ambiguities)");
114             }
115
116             // Try to resolve arguments for current constructor.
117
try {
118                 Class JavaDoc[] paramTypes = constructor.getParameterTypes();
119                 ArgumentsHolder args = createArgumentArray(
120                         beanName, mbd, resolvedValues, bw, paramTypes, constructor);
121
122                 int typeDiffWeight = args.getTypeDifferenceWeight(paramTypes);
123                 // Choose this constructor if it represents the closest match.
124
if (typeDiffWeight < minTypeDiffWeight) {
125                     constructorToUse = constructor;
126                     argsToUse = args.arguments;
127                     minTypeDiffWeight = typeDiffWeight;
128                 }
129             }
130             catch (UnsatisfiedDependencyException ex) {
131                 if (this.beanFactory.logger.isTraceEnabled()) {
132                     this.beanFactory.logger.trace("Ignoring constructor [" + constructor + "] of bean '" + beanName +
133                             "': " + ex);
134                 }
135                 if (i == candidates.length - 1 && constructorToUse == null) {
136                     throw ex;
137                 }
138                 else {
139                     // Swallow and try next constructor.
140
}
141             }
142         }
143
144         if (constructorToUse == null) {
145             throw new BeanCreationException(
146                     mbd.getResourceDescription(), beanName, "Could not resolve matching constructor");
147         }
148
149         Object JavaDoc beanInstance = this.instantiationStrategy.instantiate(
150                 mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
151         bw.setWrappedInstance(beanInstance);
152         if (this.beanFactory.logger.isDebugEnabled()) {
153             this.beanFactory.logger.debug("Bean '" + beanName + "' instantiated via constructor [" + constructorToUse + "]");
154         }
155         return bw;
156     }
157
158     /**
159      * Instantiate the bean using a named factory method. The method may be static, if the
160      * bean definition parameter specifies a class, rather than a "factory-bean", or
161      * an instance variable on a factory object itself configured using Dependency Injection.
162      * <p>Implementation requires iterating over the static or instance methods with the
163      * name specified in the RootBeanDefinition (the method may be overloaded) and trying
164      * to match with the parameters. We don't have the types attached to constructor args,
165      * so trial and error is the only way to go here. The explicitArgs array may contain
166      * argument values passed in programmatically via the corresponding getBean method.
167      * @param beanName the name of the bean
168      * @param mbd the merged bean definition for the bean
169      * @param explicitArgs argument values passed in programmatically via the getBean
170      * method, or <code>null</code> if none (-> use constructor argument values from bean definition)
171      * @return a BeanWrapper for the new instance
172      */

173     public BeanWrapper instantiateUsingFactoryMethod(String JavaDoc beanName, RootBeanDefinition mbd, Object JavaDoc[] explicitArgs) {
174         BeanWrapper bw = new BeanWrapperImpl();
175         this.beanFactory.initBeanWrapper(bw);
176
177         ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
178         ConstructorArgumentValues resolvedValues = null;
179
180         int minNrOfArgs = 0;
181         if (explicitArgs == null) {
182             // We don't have arguments passed in programmatically, so we need to resolve the
183
// arguments specified in the constructor arguments held in the bean definition.
184
resolvedValues = new ConstructorArgumentValues();
185             minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
186         }
187         else {
188             minNrOfArgs = explicitArgs.length;
189         }
190
191         boolean isStatic = true;
192         Class JavaDoc factoryClass = null;
193         Object JavaDoc factoryBean = null;
194
195         if (mbd.getFactoryBeanName() != null) {
196             factoryBean = this.beanFactory.getBean(mbd.getFactoryBeanName());
197             factoryClass = factoryBean.getClass();
198             isStatic = false;
199         }
200         else {
201             // It's a static factory method on the bean class.
202
factoryClass = mbd.getBeanClass();
203         }
204
205         // Try all methods with this name to see if they match the given arguments.
206
Method JavaDoc[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass);
207
208         Method JavaDoc factoryMethodToUse = null;
209         Object JavaDoc[] argsToUse = null;
210         int minTypeDiffWeight = Integer.MAX_VALUE;
211
212         for (int i = 0; i < candidates.length; i++) {
213             Method JavaDoc factoryMethod = candidates[i];
214
215             if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
216                     factoryMethod.getName().equals(mbd.getFactoryMethodName()) &&
217                     factoryMethod.getParameterTypes().length >= minNrOfArgs) {
218
219                 Class JavaDoc[] paramTypes = factoryMethod.getParameterTypes();
220                 ArgumentsHolder args = null;
221
222                 if (resolvedValues != null) {
223                     // Resolved contructor arguments: type conversion and/or autowiring necessary.
224
try {
225                         args = createArgumentArray(
226                                 beanName, mbd, resolvedValues, bw, paramTypes, factoryMethod);
227                     }
228                     catch (UnsatisfiedDependencyException ex) {
229                         if (this.beanFactory.logger.isTraceEnabled()) {
230                             this.beanFactory.logger.trace("Ignoring factory method [" + factoryMethod +
231                                     "] of bean '" + beanName + "': " + ex);
232                         }
233                         if (i == candidates.length - 1 && factoryMethodToUse == null) {
234                             throw ex;
235                         }
236                         else {
237                             // Swallow and try next overloaded factory method.
238
continue;
239                         }
240                     }
241                 }
242
243                 else {
244                     // Explicit arguments given -> arguments length must match exactly.
245
if (paramTypes.length != explicitArgs.length) {
246                         continue;
247                     }
248                     args = new ArgumentsHolder(explicitArgs);
249                 }
250
251                 int typeDiffWeight = args.getTypeDifferenceWeight(paramTypes);
252                 // Choose this constructor if it represents the closest match.
253
if (typeDiffWeight < minTypeDiffWeight) {
254                     factoryMethodToUse = factoryMethod;
255                     argsToUse = args.arguments;
256                     minTypeDiffWeight = typeDiffWeight;
257                 }
258             }
259         }
260         
261         if (factoryMethodToUse == null) {
262             throw new BeanDefinitionStoreException("No matching factory method found: " +
263                     (mbd.getFactoryBeanName() != null ?
264                      "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") +
265                     "factory method '" + mbd.getFactoryMethodName() + "'");
266         }
267         if (!factoryMethodToUse.isAccessible()) {
268             factoryMethodToUse.setAccessible(true);
269         }
270
271         Object JavaDoc beanInstance = this.instantiationStrategy.instantiate(
272                 mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
273         if (beanInstance == null) {
274             return null;
275         }
276
277         bw.setWrappedInstance(beanInstance);
278         if (this.beanFactory.logger.isDebugEnabled()) {
279             this.beanFactory.logger.debug(
280                     "Bean '" + beanName + "' instantiated via factory method '" + factoryMethodToUse + "'");
281         }
282         return bw;
283     }
284
285     /**
286      * Resolve the constructor arguments for this bean into the resolvedValues object.
287      * This may involve looking up other beans.
288      * This method is also used for handling invocations of static factory methods.
289      */

290     private int resolveConstructorArguments(
291             String JavaDoc beanName, RootBeanDefinition mbd, BeanWrapper bw,
292             ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {
293
294         BeanDefinitionValueResolver valueResolver =
295                 new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, bw);
296
297         int minNrOfArgs = cargs.getArgumentCount();
298
299         for (Iterator JavaDoc it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) {
300             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
301             int index = ((Integer JavaDoc) entry.getKey()).intValue();
302             if (index < 0) {
303                 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
304                         "Invalid constructor argument index: " + index);
305             }
306             if (index > minNrOfArgs) {
307                 minNrOfArgs = index + 1;
308             }
309             String JavaDoc argName = "constructor argument with index " + index;
310             ConstructorArgumentValues.ValueHolder valueHolder =
311                     (ConstructorArgumentValues.ValueHolder) entry.getValue();
312             Object JavaDoc resolvedValue = valueResolver.resolveValueIfNecessary(argName, valueHolder.getValue());
313             resolvedValues.addIndexedArgumentValue(index, resolvedValue, valueHolder.getType());
314         }
315
316         for (Iterator JavaDoc it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) {
317             ConstructorArgumentValues.ValueHolder valueHolder =
318                     (ConstructorArgumentValues.ValueHolder) it.next();
319             String JavaDoc argName = "constructor argument";
320             Object JavaDoc resolvedValue = valueResolver.resolveValueIfNecessary(argName, valueHolder.getValue());
321             resolvedValues.addGenericArgumentValue(resolvedValue, valueHolder.getType());
322         }
323
324         return minNrOfArgs;
325     }
326
327     /**
328      * Create an array of arguments to invoke a constructor or factory method,
329      * given the resolved constructor argument values.
330      */

331     private ArgumentsHolder createArgumentArray(
332             String JavaDoc beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues,
333             BeanWrapper bw, Class JavaDoc[] paramTypes, Object JavaDoc methodOrCtor)
334             throws UnsatisfiedDependencyException {
335
336         String JavaDoc methodType = (methodOrCtor instanceof Constructor JavaDoc ? "constructor" : "factory method");
337
338         ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
339         Set JavaDoc usedValueHolders = new HashSet JavaDoc(paramTypes.length);
340
341         for (int index = 0; index < paramTypes.length; index++) {
342             // Try to find matching constructor argument value, either indexed or generic.
343
ConstructorArgumentValues.ValueHolder valueHolder =
344                     resolvedValues.getArgumentValue(index, paramTypes[index], usedValueHolders);
345             // If we couldn't find a direct match and are not supposed to autowire,
346
// let's try the next generic, untyped argument value as fallback:
347
// it could match after type conversion (for example, String -> int).
348
if (valueHolder == null &&
349                     mbd.getResolvedAutowireMode() != RootBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
350                 valueHolder = resolvedValues.getGenericArgumentValue(null, usedValueHolders);
351             }
352             if (valueHolder != null) {
353                 // We found a potential match - let's give it a try.
354
// Do not consider the same value definition multiple times!
355
usedValueHolders.add(valueHolder);
356                 args.rawArguments[index] = valueHolder.getValue();
357                 try {
358                     args.arguments[index] =
359                             this.beanFactory.doTypeConversionIfNecessary(bw, args.rawArguments[index],
360                                     paramTypes[index], MethodParameter.forMethodOrConstructor(methodOrCtor, index));
361                 }
362                 catch (TypeMismatchException ex) {
363                     throw new UnsatisfiedDependencyException(
364                             mbd.getResourceDescription(), beanName, index, paramTypes[index],
365                             "Could not convert " + methodType + " argument value of type [" +
366                             ObjectUtils.nullSafeClassName(valueHolder.getValue()) +
367                             "] to required type [" + paramTypes[index].getName() + "]: " + ex.getMessage());
368                 }
369             }
370             else {
371                 // No explicit match found: we're either supposed to autowire or
372
// have to fail creating an argument array for the given constructor.
373
if (mbd.getResolvedAutowireMode() != RootBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
374                     throw new UnsatisfiedDependencyException(
375                             mbd.getResourceDescription(), beanName, index, paramTypes[index],
376                             "Ambiguous " + methodType + " argument types - " +
377                             "did you specify the correct bean references as " + methodType + " arguments?");
378                 }
379                 Map JavaDoc matchingBeans = findAutowireCandidates(beanName, paramTypes[index]);
380                 if (matchingBeans.size() != 1) {
381                     throw new UnsatisfiedDependencyException(
382                             mbd.getResourceDescription(), beanName, index, paramTypes[index],
383                             "There are " + matchingBeans.size() + " beans of type [" + paramTypes[index].getName() +
384                             "] available for autowiring: " + matchingBeans.keySet() +
385                             ". There should have been exactly 1 to be able to autowire " +
386                             methodType + " of bean '" + beanName + "'.");
387                 }
388                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) matchingBeans.entrySet().iterator().next();
389                 String JavaDoc autowiredBeanName = (String JavaDoc) entry.getKey();
390                 Object JavaDoc autowiredBean = entry.getValue();
391                 args.rawArguments[index] = autowiredBean;
392                 args.arguments[index] = autowiredBean;
393                 if (mbd.isSingleton()) {
394                     this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
395                 }
396                 if (this.beanFactory.logger.isDebugEnabled()) {
397                     this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName +
398                             "' via " + methodType + " to bean named '" + autowiredBeanName + "'");
399                 }
400             }
401         }
402         return args;
403     }
404
405
406     /**
407      * Find bean instances that match the required type.
408      * Called during autowiring for the specified bean.
409      * <p>If a subclass cannot obtain information about bean names by type,
410      * a corresponding exception should be thrown.
411      * @param beanName the name of the bean that is about to be wired
412      * @param requiredType the type of the autowired constructor argument
413      * @return a Map of candidate names and candidate instances that match
414      * the required type (never <code>null</code>)
415      * @throws BeansException in case of errors
416      * @see #autowireConstructor
417      */

418     protected abstract Map JavaDoc findAutowireCandidates(String JavaDoc beanName, Class JavaDoc requiredType) throws BeansException;
419
420
421     /**
422      * Private inner class for holding argument combinations.
423      */

424     private static class ArgumentsHolder {
425
426         public Object JavaDoc rawArguments[];
427
428         public Object JavaDoc arguments[];
429
430         public ArgumentsHolder(int size) {
431             this.rawArguments = new Object JavaDoc[size];
432             this.arguments = new Object JavaDoc[size];
433         }
434
435         public ArgumentsHolder(Object JavaDoc[] args) {
436             this.rawArguments = args;
437             this.arguments = args;
438         }
439
440         public int getTypeDifferenceWeight(Class JavaDoc[] paramTypes) {
441             // If valid arguments found, determine type difference weight.
442
// Try type difference weight on both the converted arguments and
443
// the raw arguments. If the raw weight is better, use it.
444
// Decrease raw weight by 1024 to prefer it over equal converted weight.
445
int typeDiffWeight = AutowireUtils.getTypeDifferenceWeight(paramTypes, this.arguments);
446             int rawTypeDiffWeight = AutowireUtils.getTypeDifferenceWeight(paramTypes, this.rawArguments) - 1024;
447             return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight);
448         }
449     }
450
451 }
452
Popular Tags