Search in sources :

Example 61 with BeanCreationException

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

the class ScriptFactoryPostProcessor method postProcessBeforeInstantiation.

@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    // We only apply special treatment to ScriptFactory implementations here.
    if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
        return null;
    }
    Assert.state(this.beanFactory != null, "No BeanFactory set");
    BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
    String scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
    String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
    prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);
    ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
    ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
    boolean isFactoryBean = false;
    try {
        Class<?> scriptedObjectType = scriptFactory.getScriptedObjectType(scriptSource);
        // Returned type may be null if the factory is unable to determine the type.
        if (scriptedObjectType != null) {
            isFactoryBean = FactoryBean.class.isAssignableFrom(scriptedObjectType);
        }
    } catch (Exception ex) {
        throw new BeanCreationException(beanName, "Could not determine scripted object type for " + scriptFactory, ex);
    }
    long refreshCheckDelay = resolveRefreshCheckDelay(bd);
    if (refreshCheckDelay >= 0) {
        Class<?>[] interfaces = scriptFactory.getScriptInterfaces();
        RefreshableScriptTargetSource ts = new RefreshableScriptTargetSource(this.scriptBeanFactory, scriptedObjectBeanName, scriptFactory, scriptSource, isFactoryBean);
        boolean proxyTargetClass = resolveProxyTargetClass(bd);
        String language = (String) bd.getAttribute(LANGUAGE_ATTRIBUTE);
        if (proxyTargetClass && (language == null || !language.equals("groovy"))) {
            throw new BeanDefinitionValidationException("Cannot use proxyTargetClass=true with script beans where language is not 'groovy': '" + language + "'");
        }
        ts.setRefreshCheckDelay(refreshCheckDelay);
        return createRefreshableProxy(ts, interfaces, proxyTargetClass);
    }
    if (isFactoryBean) {
        scriptedObjectBeanName = BeanFactory.FACTORY_BEAN_PREFIX + scriptedObjectBeanName;
    }
    return this.scriptBeanFactory.getBean(scriptedObjectBeanName);
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanDefinitionValidationException(org.springframework.beans.factory.support.BeanDefinitionValidationException) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) BeanDefinitionValidationException(org.springframework.beans.factory.support.BeanDefinitionValidationException) BeanCurrentlyInCreationException(org.springframework.beans.factory.BeanCurrentlyInCreationException) BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) FactoryBean(org.springframework.beans.factory.FactoryBean) ScriptSource(org.springframework.scripting.ScriptSource) ScriptFactory(org.springframework.scripting.ScriptFactory)

Example 62 with BeanCreationException

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

the class ClassPathBeanDefinitionScannerTests method testBeanNotAutowiredWithAnnotationConfigDisabled.

@Test
public void testBeanNotAutowiredWithAnnotationConfigDisabled() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
    scanner.setIncludeAnnotationConfig(false);
    scanner.setBeanNameGenerator(new TestBeanNameGenerator());
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertThat(beanCount).isGreaterThanOrEqualTo(7);
    context.refresh();
    try {
        context.getBean("fooService");
    } catch (BeanCreationException expected) {
        assertThat(expected.contains(BeanInstantiationException.class)).isTrue();
    // @Lookup method not substituted
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) BeanInstantiationException(org.springframework.beans.BeanInstantiationException) Test(org.junit.jupiter.api.Test)

Example 63 with BeanCreationException

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

the class AggressiveFactoryBeanInstantiationTests method checkLinkageError.

@Test
public void checkLinkageError() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(BeanMethodConfigurationWithExceptionInInitializer.class);
        context.refresh();
        fail("Should have thrown BeanCreationException");
    } catch (BeanCreationException ex) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(baos);
        ex.printStackTrace(pw);
        pw.flush();
        String stackTrace = baos.toString();
        assertThat(stackTrace.contains(".<clinit>")).isTrue();
        assertThat(stackTrace.contains("java.lang.NoClassDefFoundError")).isFalse();
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PrintWriter(java.io.PrintWriter) Test(org.junit.jupiter.api.Test)

Example 64 with BeanCreationException

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

the class ConstructorResolver method autowireConstructor.

/**
 * "autowire constructor" (with constructor arguments by type) behavior.
 * Also applied if explicit constructor argument values are specified,
 * matching all remaining arguments with beans from the bean factory.
 * <p>This corresponds to constructor injection: In this mode, a Spring
 * bean factory is able to host components that expect constructor-based
 * dependency resolution.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @param chosenCtors chosen candidate constructors (or {@code null} if none)
 * @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 autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);
    Constructor<?> constructorToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;
    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached constructor...
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
        }
    }
    if (constructorToUse == null || argsToUse == null) {
        // Take specified constructors, if any.
        Constructor<?>[] candidates = chosenCtors;
        if (candidates == null) {
            Class<?> beanClass = mbd.getBeanClass();
            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);
            }
        }
        if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
            Constructor<?> uniqueCandidate = candidates[0];
            if (uniqueCandidate.getParameterCount() == 0) {
                synchronized (mbd.constructorArgumentLock) {
                    mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
                    mbd.constructorArgumentsResolved = true;
                    mbd.resolvedConstructorArguments = EMPTY_ARGS;
                }
                bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                return bw;
            }
        }
        // Need to resolve the constructor.
        boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
        ConstructorArgumentValues resolvedValues = null;
        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            resolvedValues = new ConstructorArgumentValues();
            minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }
        AutowireUtils.sortConstructors(candidates);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Constructor<?>> ambiguousConstructors = null;
        Deque<UnsatisfiedDependencyException> causes = null;
        for (Constructor<?> candidate : candidates) {
            int parameterCount = candidate.getParameterCount();
            if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
                // do not look any further, there are only less greedy constructors left.
                break;
            }
            if (parameterCount < minNrOfArgs) {
                continue;
            }
            ArgumentsHolder argsHolder;
            Class<?>[] paramTypes = candidate.getParameterTypes();
            if (resolvedValues != null) {
                try {
                    String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
                    if (paramNames == null) {
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                    }
                    argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                } catch (UnsatisfiedDependencyException ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                    }
                    // Swallow and try next constructor.
                    if (causes == null) {
                        causes = new ArrayDeque<>(1);
                    }
                    causes.add(ex);
                    continue;
                }
            } else {
                // Explicit arguments given -> arguments length must match exactly.
                if (parameterCount != 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<>();
                    ambiguousConstructors.add(constructorToUse);
                }
                ambiguousConstructors.add(candidate);
            }
        }
        if (constructorToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor on bean class [" + mbd.getBeanClassName() + "] " + "(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 on bean class [" + mbd.getBeanClassName() + "] " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors);
        }
        if (explicitArgs == null && argsHolderToUse != null) {
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }
    Assert.state(argsToUse != null, "Unresolved constructor arguments");
    bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
    return bw;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) Constructor(java.lang.reflect.Constructor) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) InjectionPoint(org.springframework.beans.factory.InjectionPoint) ArrayDeque(java.util.ArrayDeque) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) BeanCreationException(org.springframework.beans.factory.BeanCreationException) NoUniqueBeanDefinitionException(org.springframework.beans.factory.NoUniqueBeanDefinitionException) BeansException(org.springframework.beans.BeansException) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) TypeMismatchException(org.springframework.beans.TypeMismatchException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException)

Example 65 with BeanCreationException

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

the class XmlBeanFactoryTests method failsOnInnerBean.

@Test
void failsOnInnerBean() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
    reader.loadBeanDefinitions(REFTYPES_CONTEXT);
    try {
        xbf.getBean("failsOnInnerBean");
    } catch (BeanCreationException ex) {
        // Check whether message contains outer bean name.
        ex.printStackTrace();
        assertThat(ex.getMessage().contains("failsOnInnerBean")).isTrue();
        assertThat(ex.getMessage().contains("someMap")).isTrue();
    }
    try {
        xbf.getBean("failsOnInnerBeanForConstructor");
    } catch (BeanCreationException ex) {
        // Check whether message contains outer bean name.
        ex.printStackTrace();
        assertThat(ex.getMessage().contains("failsOnInnerBeanForConstructor")).isTrue();
        assertThat(ex.getMessage().contains("constructor argument")).isTrue();
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) Test(org.junit.jupiter.api.Test)

Aggregations

BeanCreationException (org.springframework.beans.factory.BeanCreationException)133 Test (org.junit.Test)30 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)18 BeansException (org.springframework.beans.BeansException)16 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)13 IOException (java.io.IOException)12 Map (java.util.Map)12 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12 Test (org.junit.jupiter.api.Test)11 HashMap (java.util.HashMap)9 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)9 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)8 ArrayList (java.util.ArrayList)7 PostConstruct (javax.annotation.PostConstruct)7 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)7 Bean (org.springframework.context.annotation.Bean)7 HasId (org.apache.camel.spi.HasId)6 BeanCurrentlyInCreationException (org.springframework.beans.factory.BeanCurrentlyInCreationException)6 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)6 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)5