Search in sources :

Example 1 with BeanDefinitionStoreException

use of cn.taketoday.beans.factory.BeanDefinitionStoreException in project today-infrastructure by TAKETODAY.

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 BeanDefinition (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 merged 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(String beanName, RootBeanDefinition merged, @Nullable Object[] explicitArgs) {
    BeanWrapperImpl wrapper = new BeanWrapperImpl();
    beanFactory.initBeanWrapper(wrapper);
    boolean isStatic;
    Object factoryBean;
    Class<?> factoryClass;
    String factoryBeanName = merged.getFactoryBeanName();
    if (factoryBeanName != null) {
        if (factoryBeanName.equals(beanName)) {
            throw new BeanDefinitionStoreException(merged.getResourceDescription(), "factory-bean reference points back to the same bean definition");
        }
        factoryBean = beanFactory.getBean(factoryBeanName);
        if (merged.isSingleton() && beanFactory.containsSingleton(beanName)) {
            throw new ImplicitlyAppearedSingletonException();
        }
        beanFactory.registerDependentBean(factoryBeanName, beanName);
        factoryClass = factoryBean.getClass();
        isStatic = false;
    } else {
        // It's a static factory method on the bean class.
        if (!merged.hasBeanClass()) {
            throw new BeanDefinitionStoreException(merged.getResourceDescription(), "bean definition declares neither a bean class nor a factory-bean reference");
        }
        factoryBean = null;
        factoryClass = merged.getBeanClass();
        isStatic = true;
    }
    Method factoryMethodToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;
    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (merged.constructorArgumentLock) {
            factoryMethodToUse = (Method) merged.resolvedConstructorOrFactoryMethod;
            if (factoryMethodToUse != null && merged.constructorArgumentsResolved) {
                // Found a cached factory method...
                argsToUse = merged.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = merged.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, merged, factoryMethodToUse, argsToResolve, wrapper);
        }
    }
    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);
        List<Method> candidates = null;
        if (merged.isFactoryMethodUnique) {
            if (factoryMethodToUse == null) {
                factoryMethodToUse = merged.getResolvedFactoryMethod();
            }
            if (factoryMethodToUse != null) {
                candidates = Collections.singletonList(factoryMethodToUse);
            }
        }
        if (candidates == null) {
            candidates = new ArrayList<>();
            Method[] rawCandidates = getCandidateMethods(factoryClass, merged);
            for (Method candidate : rawCandidates) {
                if (Modifier.isStatic(candidate.getModifiers()) == isStatic && merged.isFactoryMethod(candidate)) {
                    candidates.add(candidate);
                }
            }
        }
        if (candidates.size() == 1 && explicitArgs == null && !merged.hasConstructorArgumentValues()) {
            Method uniqueCandidate = candidates.get(0);
            if (uniqueCandidate.getParameterCount() == 0) {
                merged.factoryMethodToIntrospect = uniqueCandidate;
                synchronized (merged.constructorArgumentLock) {
                    merged.resolvedConstructorOrFactoryMethod = uniqueCandidate;
                    merged.constructorArgumentsResolved = true;
                    merged.resolvedConstructorArguments = EMPTY_ARGS;
                }
                wrapper.setBeanInstance(instantiate(beanName, merged, factoryBean, uniqueCandidate, EMPTY_ARGS));
                return wrapper;
            }
        }
        if (candidates.size() > 1) {
            // explicitly skip immutable singletonList
            candidates.sort(AutowireUtils.EXECUTABLE_COMPARATOR);
        }
        ConstructorArgumentValues resolvedValues = null;
        boolean autowiring = (merged.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Method> ambiguousFactoryMethods = null;
        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            // arguments specified in the constructor arguments held in the bean definition.
            if (merged.hasConstructorArgumentValues()) {
                ConstructorArgumentValues cargs = merged.getConstructorArgumentValues();
                resolvedValues = new ConstructorArgumentValues();
                minNrOfArgs = resolveConstructorArguments(beanName, merged, wrapper, cargs, resolvedValues);
            } else {
                minNrOfArgs = 0;
            }
        }
        Deque<UnsatisfiedDependencyException> causes = null;
        for (Method candidate : candidates) {
            int parameterCount = candidate.getParameterCount();
            if (parameterCount >= minNrOfArgs) {
                ArgumentsHolder argsHolder;
                Class<?>[] paramTypes = candidate.getParameterTypes();
                if (explicitArgs != null) {
                    // Explicit arguments given -> arguments length must match exactly.
                    if (paramTypes.length != explicitArgs.length) {
                        continue;
                    }
                    argsHolder = new ArgumentsHolder(explicitArgs);
                } else {
                    // Resolved constructor arguments: type conversion and/or autowiring necessary.
                    try {
                        String[] paramNames = null;
                        ParameterNameDiscoverer pnd = beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                        argsHolder = createArgumentArray(beanName, merged, resolvedValues, paramTypes, paramNames, candidate, wrapper, autowiring, candidates.size() == 1);
                    } catch (UnsatisfiedDependencyException ex) {
                        if (log.isTraceEnabled()) {
                            log.trace("Ignoring factory method [{}] of bean '{}': {}", candidate, beanName, ex);
                        }
                        // Swallow and try next overloaded factory method.
                        if (causes == null) {
                            causes = new ArrayDeque<>(1);
                        }
                        causes.add(ex);
                        continue;
                    }
                }
                int typeDiffWeight = merged.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 && !merged.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 || argsToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            ArrayList<String> argTypes = new ArrayList<>(minNrOfArgs);
            if (explicitArgs != null) {
                for (Object arg : explicitArgs) {
                    argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
                }
            } else if (resolvedValues != null) {
                LinkedHashSet<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(merged.getResourceDescription(), beanName, "No matching factory method found on class [" + factoryClass.getName() + "]: " + (merged.getFactoryBeanName() != null ? "factory bean '" + merged.getFactoryBeanName() + "'; " : "") + "factory method '" + merged.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(merged.getResourceDescription(), beanName, "Invalid factory method '" + merged.getFactoryMethodName() + "' on class [" + factoryClass.getName() + "]: needs to have a non-void return type!");
        } else if (ambiguousFactoryMethods != null) {
            throw new BeanCreationException(merged.getResourceDescription(), beanName, "Ambiguous factory method matches found on class [" + factoryClass.getName() + "] " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousFactoryMethods);
        }
        if (explicitArgs == null && argsHolderToUse != null) {
            merged.factoryMethodToIntrospect = factoryMethodToUse;
            argsHolderToUse.storeCache(merged, factoryMethodToUse);
        }
    }
    wrapper.setBeanInstance(instantiate(beanName, merged, factoryBean, factoryMethodToUse, argsToUse));
    return wrapper;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BeanCreationException(cn.taketoday.beans.factory.BeanCreationException) BeanWrapperImpl(cn.taketoday.beans.BeanWrapperImpl) BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException) ParameterNameDiscoverer(cn.taketoday.core.ParameterNameDiscoverer) ArrayList(java.util.ArrayList) UnsatisfiedDependencyException(cn.taketoday.beans.factory.UnsatisfiedDependencyException) Method(java.lang.reflect.Method) ValueHolder(cn.taketoday.beans.factory.config.ConstructorArgumentValues.ValueHolder) InjectionPoint(cn.taketoday.beans.factory.InjectionPoint) ArrayDeque(java.util.ArrayDeque) NoUniqueBeanDefinitionException(cn.taketoday.beans.factory.NoUniqueBeanDefinitionException) NoSuchBeanDefinitionException(cn.taketoday.beans.factory.NoSuchBeanDefinitionException) BeansException(cn.taketoday.beans.BeansException) BeanCreationException(cn.taketoday.beans.factory.BeanCreationException) TypeMismatchException(cn.taketoday.beans.TypeMismatchException) UnsatisfiedDependencyException(cn.taketoday.beans.factory.UnsatisfiedDependencyException) BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException) ConstructorArgumentValues(cn.taketoday.beans.factory.config.ConstructorArgumentValues)

Example 2 with BeanDefinitionStoreException

use of cn.taketoday.beans.factory.BeanDefinitionStoreException in project today-infrastructure by TAKETODAY.

the class PlaceholderConfigurerSupport method doProcessProperties.

protected void doProcessProperties(ConfigurableBeanFactory beanFactoryToProcess, StringValueResolver valueResolver) {
    BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
    String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
    for (String curName : beanNames) {
        // to avoid failing on unresolvable placeholders in properties file locations.
        if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
            BeanDefinition definition = beanFactoryToProcess.getBeanDefinition(curName);
            try {
                visitor.visitBeanDefinition(definition);
            } catch (Exception ex) {
                throw new BeanDefinitionStoreException(definition.getResourceDescription(), curName, ex.getMessage(), ex);
            }
        }
    }
    // resolve placeholders in alias target names and aliases as well.
    beanFactoryToProcess.resolveAliases(valueResolver);
    // resolve placeholders in embedded values such as annotation attributes.
    beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
}
Also used : BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException) BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException)

Example 3 with BeanDefinitionStoreException

use of cn.taketoday.beans.factory.BeanDefinitionStoreException in project today-infrastructure by TAKETODAY.

the class XmlBeanDefinitionReader method loadBeanDefinitions.

/**
 * Load bean definitions from the specified XML file.
 *
 * @param encodedResource the resource descriptor for the XML file,
 * allowing to specify an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isTraceEnabled()) {
        logger.trace("Loading XML bean definitions from {}", encodedResource);
    }
    Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    if (!currentResources.add(encodedResource)) {
        throw new BeanDefinitionStoreException("Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
        InputSource inputSource = new InputSource(inputStream);
        if (encodedResource.getEncoding() != null) {
            inputSource.setEncoding(encodedResource.getEncoding());
        }
        return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("IOException parsing XML document from " + encodedResource.getResource(), ex);
    } finally {
        currentResources.remove(encodedResource);
        if (currentResources.isEmpty()) {
            this.resourcesCurrentlyBeingLoaded.remove();
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException) InputStream(java.io.InputStream) IOException(java.io.IOException) EncodedResource(cn.taketoday.core.io.EncodedResource)

Example 4 with BeanDefinitionStoreException

use of cn.taketoday.beans.factory.BeanDefinitionStoreException in project today-infrastructure by TAKETODAY.

the class ClassPathBeanDefinitionScanner method scan.

/**
 * Perform a scan within the specified base packages and consume the registered
 * bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 *
 * @param operator set of beans registered if any for tooling registration purposes
 * @param basePackages the packages to check for annotated classes
 */
public void scan(@Nullable UnaryOperator<BeanDefinitionHolder> operator, String... basePackages) {
    for (String basePackage : basePackages) {
        try {
            scanCandidateComponents(basePackage, (metadataReader, factory) -> {
                ScannedGenericBeanDefinition candidate = new ScannedGenericBeanDefinition(metadataReader);
                Resource resource = metadataReader.getResource();
                candidate.setSource(resource);
                candidate.setResource(resource);
                ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(candidate);
                candidate.setScope(scopeMetadata.getScopeName());
                String beanName = beanNameGenerator.generateBeanName(candidate, registry);
                postProcessBeanDefinition(candidate, beanName);
                AnnotationConfigUtils.processCommonDefinitionAnnotations(candidate);
                if (checkCandidate(beanName, candidate)) {
                    BeanDefinitionHolder holder = new BeanDefinitionHolder(candidate, beanName);
                    holder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, holder, registry);
                    if (operator != null) {
                        holder = operator.apply(holder);
                    }
                    registerBeanDefinition(holder, registry);
                }
            });
        } catch (IOException ex) {
            throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
        }
    }
}
Also used : ScopeMetadata(cn.taketoday.context.loader.ScopeMetadata) BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException) BeanDefinitionHolder(cn.taketoday.beans.factory.config.BeanDefinitionHolder) Resource(cn.taketoday.core.io.Resource) IOException(java.io.IOException)

Example 5 with BeanDefinitionStoreException

use of cn.taketoday.beans.factory.BeanDefinitionStoreException in project today-framework by TAKETODAY.

the class PlaceholderConfigurerSupport method doProcessProperties.

protected void doProcessProperties(ConfigurableBeanFactory beanFactoryToProcess, StringValueResolver valueResolver) {
    BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
    String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
    for (String curName : beanNames) {
        // to avoid failing on unresolvable placeholders in properties file locations.
        if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
            BeanDefinition definition = beanFactoryToProcess.getBeanDefinition(curName);
            try {
                visitor.visitBeanDefinition(definition);
            } catch (Exception ex) {
                throw new BeanDefinitionStoreException(definition.getResourceDescription(), curName, ex.getMessage(), ex);
            }
        }
    }
    // resolve placeholders in alias target names and aliases as well.
    beanFactoryToProcess.resolveAliases(valueResolver);
    // resolve placeholders in embedded values such as annotation attributes.
    beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
}
Also used : BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException) BeanDefinitionStoreException(cn.taketoday.beans.factory.BeanDefinitionStoreException)

Aggregations

BeanDefinitionStoreException (cn.taketoday.beans.factory.BeanDefinitionStoreException)17 IOException (java.io.IOException)10 BeanDefinitionHolder (cn.taketoday.beans.factory.config.BeanDefinitionHolder)5 LinkedHashSet (java.util.LinkedHashSet)5 ScopeMetadata (cn.taketoday.context.loader.ScopeMetadata)4 AbstractBeanDefinition (cn.taketoday.beans.factory.support.AbstractBeanDefinition)3 BeanWrapperImpl (cn.taketoday.beans.BeanWrapperImpl)2 BeansException (cn.taketoday.beans.BeansException)2 TypeMismatchException (cn.taketoday.beans.TypeMismatchException)2 BeanCreationException (cn.taketoday.beans.factory.BeanCreationException)2 InjectionPoint (cn.taketoday.beans.factory.InjectionPoint)2 NoSuchBeanDefinitionException (cn.taketoday.beans.factory.NoSuchBeanDefinitionException)2 NoUniqueBeanDefinitionException (cn.taketoday.beans.factory.NoUniqueBeanDefinitionException)2 UnsatisfiedDependencyException (cn.taketoday.beans.factory.UnsatisfiedDependencyException)2 AnnotatedBeanDefinition (cn.taketoday.beans.factory.annotation.AnnotatedBeanDefinition)2 ConstructorArgumentValues (cn.taketoday.beans.factory.config.ConstructorArgumentValues)2 ValueHolder (cn.taketoday.beans.factory.config.ConstructorArgumentValues.ValueHolder)2 BeanComponentDefinition (cn.taketoday.beans.factory.parsing.BeanComponentDefinition)2 ScannedGenericBeanDefinition (cn.taketoday.context.annotation.ScannedGenericBeanDefinition)2 ParameterNameDiscoverer (cn.taketoday.core.ParameterNameDiscoverer)2