Package org.springframework.beans.factory

Examples of org.springframework.beans.factory.BeanCreationException


    try {
      invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
      throw new BeanCreationException(
          (mbd != null ? mbd.getResourceDescription() : null),
          beanName, "Invocation of init method failed", ex);
    }

    if (mbd == null || !mbd.isSynthetic()) {
View Full Code Here


            elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
            array.resolvedElementType = elementType;
          }
          catch (Throwable ex) {
            // Improve the message by showing the context.
            throw new BeanCreationException(
                this.beanDefinition.getResourceDescription(), this.beanName,
                "Error resolving array type for " + argName, ex);
          }
        }
        else {
          elementType = Object.class;
        }
      }
      return resolveManagedArray(argName, (List<?>) value, elementType);
    }
    else if (value instanceof ManagedList) {
      // May need to resolve contained runtime references.
      return resolveManagedList(argName, (List<?>) value);
    }
    else if (value instanceof ManagedSet) {
      // May need to resolve contained runtime references.
      return resolveManagedSet(argName, (Set<?>) value);
    }
    else if (value instanceof ManagedMap) {
      // May need to resolve contained runtime references.
      return resolveManagedMap(argName, (Map<?, ?>) value);
    }
    else if (value instanceof ManagedProperties) {
      Properties original = (Properties) value;
      Properties copy = new Properties();
      for (Map.Entry propEntry : original.entrySet()) {
        Object propKey = propEntry.getKey();
        Object propValue = propEntry.getValue();
        if (propKey instanceof TypedStringValue) {
          propKey = evaluate((TypedStringValue) propKey);
        }
        if (propValue instanceof TypedStringValue) {
          propValue = evaluate((TypedStringValue) propValue);
        }
        copy.put(propKey, propValue);
      }
      return copy;
    }
    else if (value instanceof TypedStringValue) {
      // Convert value to target type here.
      TypedStringValue typedStringValue = (TypedStringValue) value;
      Object valueObject = evaluate(typedStringValue);
      try {
        Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
        if (resolvedTargetType != null) {
          return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
        }
        else {
          return valueObject;
        }
      }
      catch (Throwable ex) {
        // Improve the message by showing the context.
        throw new BeanCreationException(
            this.beanDefinition.getResourceDescription(), this.beanName,
            "Error converting typed String value for " + argName, ex);
      }
    }
    else {
View Full Code Here

      else {
        return innerBean;
      }
    }
    catch (BeansException ex) {
      throw new BeanCreationException(
          this.beanDefinition.getResourceDescription(), this.beanName,
          "Cannot create inner bean '" + innerBeanName + "' " +
          (mbd != null && mbd.getBeanClassName() != null ? "of type [" + mbd.getBeanClassName() + "] " : "") +
          "while setting " + argName, ex);
    }
View Full Code Here

    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 '" + refName +
              "' in parent factory: no parent factory available");
        }
        return this.beanFactory.getParentBeanFactory().getBean(refName);
      }
      else {
        Object bean = this.beanFactory.getBean(refName);
        this.beanFactory.registerDependentBean(refName, this.beanName);
        return bean;
      }
    }
    catch (BeansException ex) {
      throw new BeanCreationException(
          this.beanDefinition.getResourceDescription(), this.beanName,
          "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
    }
  }
View Full Code Here

    InjectionMetadata metadata = findResourceMetadata(bean.getClass());
    try {
      metadata.inject(bean, beanName, pvs);
    }
    catch (Throwable ex) {
      throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
    }
    return pvs;
  }
View Full Code Here

    LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
    try {
      metadata.invokeInitMethods(bean, beanName);
    }
    catch (InvocationTargetException ex) {
      throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
    }
    catch (Throwable ex) {
      throw new BeanCreationException(beanName, "Couldn't invoke init method", ex);
    }
    return bean;
  }
View Full Code Here

        try {
          candidates = (mbd.isNonPublicAccessAllowed() ?
              beanClass.getDeclaredConstructors() : beanClass.getConstructors());
        }
        catch (Throwable ex) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName,
              "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                  "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
        }
      }
      AutowireUtils.sortConstructors(candidates);
      int minTypeDiffWeight = Integer.MAX_VALUE;
      Set<Constructor> ambiguousConstructors = null;
      List<Exception> causes = null;

      for (int i = 0; i < candidates.length; i++) {
        Constructor<?> candidate = candidates[i];
        Class[] paramTypes = candidate.getParameterTypes();

        if (constructorToUse != null && argsToUse.length > paramTypes.length) {
          // Already found greedy constructor that can be satisfied ->
          // do not look any further, there are only less greedy constructors left.
          break;
        }
        if (paramTypes.length < minNrOfArgs) {
          continue;
        }

        ArgumentsHolder argsHolder;
        if (resolvedValues != null) {
          try {
            String[] paramNames = null;
            if (constructorPropertiesAnnotationAvailable) {
              paramNames = ConstructorPropertiesChecker.evaluateAnnotation(candidate, paramTypes.length);
            }
            if (paramNames == null) {
              ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
              if (pnd != null) {
                paramNames = pnd.getParameterNames(candidate);
              }
            }
            argsHolder = createArgumentArray(
                beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring);
          }
          catch (UnsatisfiedDependencyException ex) {
            if (this.beanFactory.logger.isTraceEnabled()) {
              this.beanFactory.logger.trace(
                  "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
            }
            if (i == candidates.length - 1 && constructorToUse == null) {
              if (causes != null) {
                for (Exception cause : causes) {
                  this.beanFactory.onSuppressedException(cause);
                }
              }
              throw ex;
            }
            else {
              // Swallow and try next constructor.
              if (causes == null) {
                causes = new LinkedList<Exception>();
              }
              causes.add(ex);
              continue;
            }
          }
        }
        else {
          // Explicit arguments given -> arguments length must match exactly.
          if (paramTypes.length != explicitArgs.length) {
            continue;
          }
          argsHolder = new ArgumentsHolder(explicitArgs);
        }

        int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
            argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
        // Choose this constructor if it represents the closest match.
        if (typeDiffWeight < minTypeDiffWeight) {
          constructorToUse = candidate;
          argsHolderToUse = argsHolder;
          argsToUse = argsHolder.arguments;
          minTypeDiffWeight = typeDiffWeight;
          ambiguousConstructors = null;
        }
        else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
          if (ambiguousConstructors == null) {
            ambiguousConstructors = new LinkedHashSet<Constructor>();
            ambiguousConstructors.add(constructorToUse);
          }
          ambiguousConstructors.add(candidate);
        }
      }

      if (constructorToUse == null) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Could not resolve matching constructor " +
            "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
      }
      else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Ambiguous constructor matches found in bean '" + beanName + "' " +
            "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
            ambiguousConstructors);
      }

      if (explicitArgs == null) {
        argsHolderToUse.storeCache(mbd, constructorToUse);
      }
    }

    try {
      Object beanInstance;

      if (System.getSecurityManager() != null) {
        final Constructor ctorToUse = constructorToUse;
        final Object[] argumentsToUse = argsToUse;
        beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
          public Object run() {
            return beanFactory.getInstantiationStrategy().instantiate(
                mbd, beanName, beanFactory, ctorToUse, argumentsToUse);
          }
        }, beanFactory.getAccessControlContext());
      }
      else {
        beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
            mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
      }
     
      bw.setWrappedInstance(beanInstance);
      return bw;
    }
    catch (Throwable ex) {
      throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
  }
View Full Code Here

        throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
            "factory-bean reference points back to the same bean definition");
      }
      factoryBean = this.beanFactory.getBean(factoryBeanName);
      if (factoryBean == null) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "factory-bean '" + factoryBeanName + "' returned null");
      }
      factoryClass = factoryBean.getClass();
      isStatic = false;
    }
    else {
      // It's a static factory method on the bean class.
      if (!mbd.hasBeanClass()) {
        throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
            "bean definition declares neither a bean class nor a factory-bean reference");
      }
      factoryBean = null;
      factoryClass = mbd.getBeanClass();
      isStatic = true;
    }

    Method factoryMethodToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;

    if (explicitArgs != null) {
      argsToUse = explicitArgs;
    }
    else {
      Object[] argsToResolve = null;
      synchronized (mbd.constructorArgumentLock) {
        factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
        if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
          // Found a cached factory method...
          argsToUse = mbd.resolvedConstructorArguments;
          if (argsToUse == null) {
            argsToResolve = mbd.preparedConstructorArguments;
          }
        }
      }
      if (argsToResolve != null) {
        argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve);
      }
    }

    if (factoryMethodToUse == null || argsToUse == null) {
      // Need to determine the factory method...
      // Try all methods with this name to see if they match the given arguments.
      factoryClass = ClassUtils.getUserClass(factoryClass);
      Method[] rawCandidates;

      final Class factoryClazz = factoryClass;
      if (System.getSecurityManager() != null) {
        rawCandidates = AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
          public Method[] run() {
            return (mbd.isNonPublicAccessAllowed() ?
                ReflectionUtils.getAllDeclaredMethods(factoryClazz) : factoryClazz.getMethods());
          }
        });
      }
      else {
        rawCandidates = (mbd.isNonPublicAccessAllowed() ?
            ReflectionUtils.getAllDeclaredMethods(factoryClazz) : factoryClazz.getMethods());
      }
     
      List<Method> candidateSet = new ArrayList<Method>();
      for (Method candidate : rawCandidates) {
        if (Modifier.isStatic(candidate.getModifiers()) == isStatic &&
            candidate.getName().equals(mbd.getFactoryMethodName()) &&
            mbd.isFactoryMethod(candidate)) {
          candidateSet.add(candidate);
        }
      }
      Method[] candidates = candidateSet.toArray(new Method[candidateSet.size()]);
      AutowireUtils.sortFactoryMethods(candidates);

      ConstructorArgumentValues resolvedValues = null;
      boolean autowiring = (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
      int minTypeDiffWeight = Integer.MAX_VALUE;
      Set<Method> ambiguousFactoryMethods = null;

      int minNrOfArgs;
      if (explicitArgs != null) {
        minNrOfArgs = explicitArgs.length;
      }
      else {
        // We don't have arguments passed in programmatically, so we need to resolve the
        // arguments specified in the constructor arguments held in the bean definition.
        ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
        resolvedValues = new ConstructorArgumentValues();
        minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
      }

      List<Exception> causes = null;

      for (int i = 0; i < candidates.length; i++) {
        Method candidate = candidates[i];
        Class[] paramTypes = candidate.getParameterTypes();

        if (paramTypes.length >= minNrOfArgs) {
          ArgumentsHolder argsHolder;

          if (resolvedValues != null) {
            // Resolved constructor arguments: type conversion and/or autowiring necessary.
            try {
              String[] paramNames = null;
              ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
              if (pnd != null) {
                paramNames = pnd.getParameterNames(candidate);
              }
              argsHolder = createArgumentArray(
                  beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring);
            }
            catch (UnsatisfiedDependencyException ex) {
              if (this.beanFactory.logger.isTraceEnabled()) {
                this.beanFactory.logger.trace("Ignoring factory method [" + candidate +
                    "] of bean '" + beanName + "': " + ex);
              }
              if (i == candidates.length - 1 && argsHolderToUse == null) {
                if (causes != null) {
                  for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                  }
                }
                throw ex;
              }
              else {
                // Swallow and try next overloaded factory method.
                if (causes == null) {
                  causes = new LinkedList<Exception>();
                }
                causes.add(ex);
                continue;
              }
            }
          }

          else {
            // Explicit arguments given -> arguments length must match exactly.
            if (paramTypes.length != explicitArgs.length) {
              continue;
            }
            argsHolder = new ArgumentsHolder(explicitArgs);
          }

          int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
              argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
          // Choose this factory method if it represents the closest match.
          if (typeDiffWeight < minTypeDiffWeight) {
            factoryMethodToUse = candidate;
            argsHolderToUse = argsHolder;
            argsToUse = argsHolder.arguments;
            minTypeDiffWeight = typeDiffWeight;
            ambiguousFactoryMethods = null;
          }
          else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight) {
            if (ambiguousFactoryMethods == null) {
              ambiguousFactoryMethods = new LinkedHashSet<Method>();
              ambiguousFactoryMethods.add(factoryMethodToUse);
            }
            ambiguousFactoryMethods.add(candidate);
          }
        }
      }

      if (factoryMethodToUse == null) {
        boolean hasArgs = (resolvedValues.getArgumentCount() > 0);
        String argDesc = "";
        if (hasArgs) {
          List<String> argTypes = new ArrayList<String>();
          for (ValueHolder value : resolvedValues.getIndexedArgumentValues().values()) {
            String argType = (value.getType() != null ?
                ClassUtils.getShortName(value.getType()) : value.getValue().getClass().getSimpleName());
            argTypes.add(argType);
          }
          argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
        }
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "No matching factory method found: " +
            (mbd.getFactoryBeanName() != null ?
              "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") +
            "factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. " +
            "Check that a method with the specified name " +
            (hasArgs ? "and arguments " : "") +
            "exists and that it is " +
            (isStatic ? "static" : "non-static") + ".");
      }
      else if (void.class.equals(factoryMethodToUse.getReturnType())) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Invalid factory method '" + mbd.getFactoryMethodName() +
            "': needs to have a non-void return type!");
      }
      else if (ambiguousFactoryMethods != null && !mbd.isLenientConstructorResolution()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Ambiguous factory method matches found in bean '" + beanName + "' " +
            "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
            ambiguousFactoryMethods);
      }

      if (explicitArgs == null && argsHolderToUse != null) {
        argsHolderToUse.storeCache(mbd, factoryMethodToUse);
      }
    }

    try {
      Object beanInstance;

      if (System.getSecurityManager() != null) {
        final Object fb = factoryBean;
        final Method factoryMethod = factoryMethodToUse;
        final Object[] args = argsToUse;
        beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
          public Object run() {
            return beanFactory.getInstantiationStrategy().instantiate(
                mbd, beanName, beanFactory, fb, factoryMethod, args);
          }
        }, beanFactory.getAccessControlContext());
      }
      else {
        beanInstance = beanFactory.getInstantiationStrategy().instantiate(
            mbd, beanName, beanFactory, factoryBean, factoryMethodToUse, argsToUse);
      }
     
      if (beanInstance == null) {
        return null;
      }
      bw.setWrappedInstance(beanInstance);
      return bw;
    }
    catch (Throwable ex) {
      throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
  }
View Full Code Here

    int minNrOfArgs = cargs.getArgumentCount();

    for (Map.Entry<Integer, ConstructorArgumentValues.ValueHolder> entry : cargs.getIndexedArgumentValues().entrySet()) {
      int index = entry.getKey();
      if (index < 0) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Invalid constructor argument index: " + index);
      }
      if (index > minNrOfArgs) {
        minNrOfArgs = index + 1;
      }
View Full Code Here

    }
    catch (FactoryBeanNotInitializedException ex) {
      throw new BeanCurrentlyInCreationException(beanName, ex.toString());
    }
    catch (Throwable ex) {
      throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
    }

   
    // Do not accept a null value for a FactoryBean that's not fully
    // initialized yet: Many FactoryBeans just return null then.
    if (object == null && isSingletonCurrentlyInCreation(beanName)) {
      throw new BeanCurrentlyInCreationException(
          beanName, "FactoryBean which is currently in creation returned null from getObject");
    }

    if (object != null && shouldPostProcess) {
      try {
        object = postProcessObjectFromFactoryBean(object, beanName);
      }
      catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex);
      }
    }

    return object;
  }
View Full Code Here

TOP

Related Classes of org.springframework.beans.factory.BeanCreationException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.