Search in sources :

Example 26 with BeanDefinitionStoreException

use of org.springframework.beans.factory.BeanDefinitionStoreException in project spring-framework by spring-projects.

the class BeanDefinitionValueResolver method resolveValueIfNecessary.

/**
	 * Given a PropertyValue, return a value, resolving any references to other
	 * beans in the factory if necessary. The value could be:
	 * <li>A BeanDefinition, which leads to the creation of a corresponding
	 * new bean instance. Singleton flags and names of such "inner beans"
	 * are always ignored: Inner beans are anonymous prototypes.
	 * <li>A RuntimeBeanReference, which must be resolved.
	 * <li>A ManagedList. This is a special collection that may contain
	 * RuntimeBeanReferences or Collections that will need to be resolved.
	 * <li>A ManagedSet. May also contain RuntimeBeanReferences or
	 * Collections that will need to be resolved.
	 * <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
	 * or Collection that will need to be resolved.
	 * <li>An ordinary object or {@code null}, in which case it's left alone.
	 * @param argName the name of the argument that the value is defined for
	 * @param value the value object to resolve
	 * @return the resolved object
	 */
public Object resolveValueIfNecessary(Object argName, Object value) {
    // to another bean to be resolved.
    if (value instanceof RuntimeBeanReference) {
        RuntimeBeanReference ref = (RuntimeBeanReference) value;
        return resolveReference(argName, ref);
    } else if (value instanceof RuntimeBeanNameReference) {
        String refName = ((RuntimeBeanNameReference) value).getBeanName();
        refName = String.valueOf(doEvaluate(refName));
        if (!this.beanFactory.containsBean(refName)) {
            throw new BeanDefinitionStoreException("Invalid bean name '" + refName + "' in bean reference for " + argName);
        }
        return refName;
    } else if (value instanceof BeanDefinitionHolder) {
        // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
        BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
        return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
    } else if (value instanceof BeanDefinition) {
        // Resolve plain BeanDefinition, without contained name: use dummy name.
        BeanDefinition bd = (BeanDefinition) value;
        String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(bd);
        return resolveInnerBean(argName, innerBeanName, bd);
    } else if (value instanceof ManagedArray) {
        // May need to resolve contained runtime references.
        ManagedArray array = (ManagedArray) value;
        Class<?> elementType = array.resolvedElementType;
        if (elementType == null) {
            String elementTypeName = array.getElementTypeName();
            if (StringUtils.hasText(elementTypeName)) {
                try {
                    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<Object, Object> 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 {
        return evaluate(value);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Properties(java.util.Properties) RuntimeBeanNameReference(org.springframework.beans.factory.config.RuntimeBeanNameReference) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) ArrayList(java.util.ArrayList) List(java.util.List) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 27 with BeanDefinitionStoreException

use of org.springframework.beans.factory.BeanDefinitionStoreException in project spring-framework by spring-projects.

the class ConstructorResolver method instantiateUsingFactoryMethod.

/**
	 * Instantiate the bean using a named factory method. The method may be static, if the
	 * bean definition parameter specifies a class, rather than a "factory-bean", or
	 * an instance variable on a factory object itself configured using Dependency Injection.
	 * <p>Implementation requires iterating over the static or instance methods with the
	 * name specified in the RootBeanDefinition (the method may be overloaded) and trying
	 * to match with the parameters. We don't have the types attached to constructor args,
	 * so trial and error is the only way to go here. The explicitArgs array may contain
	 * argument values passed in programmatically via the corresponding getBean method.
	 * @param beanName the name of the bean
	 * @param mbd the merged bean definition for the bean
	 * @param explicitArgs argument values passed in programmatically via the getBean
	 * method, or {@code null} if none (-> use constructor argument values from bean definition)
	 * @return a BeanWrapper for the new instance
	 */
public BeanWrapper instantiateUsingFactoryMethod(final String beanName, final RootBeanDefinition mbd, final Object[] explicitArgs) {
    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);
    Object factoryBean;
    Class<?> factoryClass;
    boolean isStatic;
    String factoryBeanName = mbd.getFactoryBeanName();
    if (factoryBeanName != null) {
        if (factoryBeanName.equals(beanName)) {
            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 + "' (or a BeanPostProcessor involved) returned null");
        }
        if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
            throw new ImplicitlyAppearedSingletonException();
        }
        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 = getCandidateMethods(factoryClass, mbd);
        List<Method> candidateSet = new ArrayList<>();
        for (Method candidate : rawCandidates) {
            if (Modifier.isStatic(candidate.getModifiers()) == isStatic && 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);
        }
        LinkedList<UnsatisfiedDependencyException> causes = null;
        for (Method candidate : candidates) {
            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);
                        }
                        // Swallow and try next overloaded factory method.
                        if (causes == null) {
                            causes = new LinkedList<>();
                        }
                        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 // and explicitly ignore overridden methods (with the same parameter signature).
                if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight && !mbd.isLenientConstructorResolution() && paramTypes.length == factoryMethodToUse.getParameterCount() && !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
                    if (ambiguousFactoryMethods == null) {
                        ambiguousFactoryMethods = new LinkedHashSet<>();
                        ambiguousFactoryMethods.add(factoryMethodToUse);
                    }
                    ambiguousFactoryMethods.add(candidate);
                }
            }
        }
        if (factoryMethodToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            List<String> argTypes = new ArrayList<>(minNrOfArgs);
            if (explicitArgs != null) {
                for (Object arg : explicitArgs) {
                    argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
                }
            } else {
                Set<ValueHolder> valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
                valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
                valueHolders.addAll(resolvedValues.getGenericArgumentValues());
                for (ValueHolder value : valueHolders) {
                    String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) : (value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null"));
                    argTypes.add(argType);
                }
            }
            String 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 " + (minNrOfArgs > 0 ? "and arguments " : "") + "exists and that it is " + (isStatic ? "static" : "non-static") + ".");
        } else if (void.class == 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) {
            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>() {

                @Override
                public Object run() {
                    return beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, beanFactory, fb, factoryMethod, args);
                }
            }, beanFactory.getAccessControlContext());
        } else {
            beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
        }
        if (beanInstance == null) {
            return null;
        }
        bw.setBeanInstance(beanInstance);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via factory method failed", ex);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) ArrayList(java.util.ArrayList) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) PrivilegedAction(java.security.PrivilegedAction) Method(java.lang.reflect.Method) ValueHolder(org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder) InjectionPoint(org.springframework.beans.factory.InjectionPoint) LinkedList(java.util.LinkedList) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeansException(org.springframework.beans.BeansException) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) TypeMismatchException(org.springframework.beans.TypeMismatchException) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues)

Example 28 with BeanDefinitionStoreException

use of org.springframework.beans.factory.BeanDefinitionStoreException in project spring-framework by spring-projects.

the class AbstractAutowireCapableBeanFactory method getTypeForFactoryMethod.

/**
	 * Determine the target type for the given bean definition which is based on
	 * a factory method. Only called if there is no singleton instance registered
	 * for the target bean already.
	 * <p>This implementation determines the type matching {@link #createBean}'s
	 * different creation strategies. As far as possible, we'll perform static
	 * type checking to avoid creation of the target bean.
	 * @param beanName the name of the bean (for error handling purposes)
	 * @param mbd the merged bean definition for the bean
	 * @param typesToMatch the types to match in case of internal type matching purposes
	 * (also signals that the returned {@code Class} will never be exposed to application code)
	 * @return the type for the bean if determinable, or {@code null} otherwise
	 * @see #createBean
	 */
protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    ResolvableType cachedReturnType = mbd.factoryMethodReturnType;
    if (cachedReturnType != null) {
        return cachedReturnType.resolve();
    }
    Class<?> factoryClass;
    boolean isStatic = true;
    String factoryBeanName = mbd.getFactoryBeanName();
    if (factoryBeanName != null) {
        if (factoryBeanName.equals(beanName)) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition");
        }
        // Check declared factory method return type on factory class.
        factoryClass = getType(factoryBeanName);
        isStatic = false;
    } else {
        // Check declared factory method return type on bean class.
        factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
    }
    if (factoryClass == null) {
        return null;
    }
    factoryClass = ClassUtils.getUserClass(factoryClass);
    // If all factory methods have the same return type, return that type.
    // Can't clearly figure out exact method due to type converting / autowiring!
    Class<?> commonType = null;
    Method uniqueCandidate = null;
    int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount();
    Method[] candidates = ReflectionUtils.getUniqueDeclaredMethods(factoryClass);
    for (Method factoryMethod : candidates) {
        if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic && factoryMethod.getName().equals(mbd.getFactoryMethodName()) && factoryMethod.getParameterCount() >= minNrOfArgs) {
            // Declared type variables to inspect?
            if (factoryMethod.getTypeParameters().length > 0) {
                try {
                    // Fully resolve parameter names and argument values.
                    Class<?>[] paramTypes = factoryMethod.getParameterTypes();
                    String[] paramNames = null;
                    ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
                    if (pnd != null) {
                        paramNames = pnd.getParameterNames(factoryMethod);
                    }
                    ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
                    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
                    Object[] args = new Object[paramTypes.length];
                    for (int i = 0; i < args.length; i++) {
                        ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders);
                        if (valueHolder == null) {
                            valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders);
                        }
                        if (valueHolder != null) {
                            args[i] = valueHolder.getValue();
                            usedValueHolders.add(valueHolder);
                        }
                    }
                    Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(factoryMethod, args, getBeanClassLoader());
                    if (returnType != null) {
                        uniqueCandidate = (commonType == null ? factoryMethod : null);
                        commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
                        if (commonType == null) {
                            // Ambiguous return types found: return null to indicate "not determinable".
                            return null;
                        }
                    }
                } catch (Throwable ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Failed to resolve generic return type for factory method: " + ex);
                    }
                }
            } else {
                uniqueCandidate = (commonType == null ? factoryMethod : null);
                commonType = ClassUtils.determineCommonAncestor(factoryMethod.getReturnType(), commonType);
                if (commonType == null) {
                    // Ambiguous return types found: return null to indicate "not determinable".
                    return null;
                }
            }
        }
    }
    if (commonType != null) {
        // Clear return type found: all factory methods return same type.
        mbd.factoryMethodReturnType = (uniqueCandidate != null ? ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType));
    }
    return commonType;
}
Also used : BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) DefaultParameterNameDiscoverer(org.springframework.core.DefaultParameterNameDiscoverer) Method(java.lang.reflect.Method) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) ResolvableType(org.springframework.core.ResolvableType) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 29 with BeanDefinitionStoreException

use of org.springframework.beans.factory.BeanDefinitionStoreException in project spring-framework by spring-projects.

the class DefaultBeanDefinitionDocumentReader method importBeanDefinitionResource.

/**
	 * Parse an "import" element and load the bean definitions
	 * from the given resource into the bean factory.
	 */
protected void importBeanDefinitionResource(Element ele) {
    String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
    if (!StringUtils.hasText(location)) {
        getReaderContext().error("Resource location must not be empty", ele);
        return;
    }
    // Resolve system properties: e.g. "${user.dir}"
    location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
    Set<Resource> actualResources = new LinkedHashSet<>(4);
    // Discover whether the location is an absolute or relative URI
    boolean absoluteLocation = false;
    try {
        absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
    } catch (URISyntaxException ex) {
    // cannot convert to an URI, considering the location relative
    // unless it is the well-known Spring prefix "classpath*:"
    }
    // Absolute or relative?
    if (absoluteLocation) {
        try {
            int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
            if (logger.isDebugEnabled()) {
                logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
            }
        } catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to import bean definitions from URL location [" + location + "]", ele, ex);
        }
    } else {
        // No URL -> considering resource location as relative to the current file.
        try {
            int importCount;
            Resource relativeResource = getReaderContext().getResource().createRelative(location);
            if (relativeResource.exists()) {
                importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
                actualResources.add(relativeResource);
            } else {
                String baseLocation = getReaderContext().getResource().getURL().toString();
                importCount = getReaderContext().getReader().loadBeanDefinitions(StringUtils.applyRelativePath(baseLocation, location), actualResources);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
            }
        } catch (IOException ex) {
            getReaderContext().error("Failed to resolve current resource location", ele, ex);
        } catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]", ele, ex);
        }
    }
    Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
    getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) Resource(org.springframework.core.io.Resource) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 30 with BeanDefinitionStoreException

use of org.springframework.beans.factory.BeanDefinitionStoreException in project spring-framework by spring-projects.

the class DefaultListableBeanFactory method doGetBeanNamesForType.

private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
    List<String> result = new ArrayList<>();
    // Check all bean definitions.
    for (String beanName : this.beanDefinitionNames) {
        // 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() || isAllowEagerClassLoading())) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) {
                    // In case of FactoryBean, match object created by FactoryBean.
                    boolean isFactoryBean = isFactoryBean(beanName, mbd);
                    BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
                    boolean matchFound = (allowEagerInit || !isFactoryBean || (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) && (includeNonSingletons || (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) && isTypeMatch(beanName, type);
                    if (!matchFound && isFactoryBean) {
                        // In case of FactoryBean, try to match FactoryBean instance itself next.
                        beanName = FACTORY_BEAN_PREFIX + beanName;
                        matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
                    }
                    if (matchFound) {
                        result.add(beanName);
                    }
                }
            } catch (CannotLoadBeanClassException ex) {
                if (allowEagerInit) {
                    throw ex;
                }
                // Probably contains a placeholder: let's ignore it for type matching purposes.
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
                }
                onSuppressedException(ex);
            } catch (BeanDefinitionStoreException ex) {
                if (allowEagerInit) {
                    throw ex;
                }
                // Probably contains a placeholder: let's ignore it for type matching purposes.
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
                }
                onSuppressedException(ex);
            }
        }
    }
    // Check manually registered singletons too.
    for (String beanName : this.manualSingletonNames) {
        try {
            // In case of FactoryBean, match object created by FactoryBean.
            if (isFactoryBean(beanName)) {
                if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
                    result.add(beanName);
                    // Match found for this bean: do not match FactoryBean itself anymore.
                    continue;
                }
                // In case of FactoryBean, try to match FactoryBean itself next.
                beanName = FACTORY_BEAN_PREFIX + beanName;
            }
            // Match raw bean instance (might be raw FactoryBean).
            if (isTypeMatch(beanName, type)) {
                result.add(beanName);
            }
        } catch (NoSuchBeanDefinitionException ex) {
            // Shouldn't happen - probably a result of circular reference resolution...
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to check manually registered singleton with name '" + beanName + "'", ex);
            }
        }
    }
    return StringUtils.toStringArray(result);
}
Also used : BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) ArrayList(java.util.ArrayList) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Aggregations

BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)39 Test (org.junit.Test)14 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)11 IOException (java.io.IOException)8 LinkedHashSet (java.util.LinkedHashSet)6 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)5 MockServletContext (org.springframework.mock.web.test.MockServletContext)5 ArrayList (java.util.ArrayList)4 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)4 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)4 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)4 Map (java.util.Map)3 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)3 BeanCreationException (org.springframework.beans.factory.BeanCreationException)3 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)3 AnnotatedBeanDefinition (org.springframework.beans.factory.annotation.AnnotatedBeanDefinition)3 Resource (org.springframework.core.io.Resource)3 Method (java.lang.reflect.Method)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2