Search in sources :

Example 1 with BeanCreationException

use of org.springframework.beans.factory.BeanCreationException in project cas by apereo.

the class Beans method newMongoDbClientOptionsFactoryBean.

/**
     * New mongo db client options factory bean.
     *
     * @param mongo the mongo properties.
     * @return the mongo client options factory bean
     */
public static MongoClientOptionsFactoryBean newMongoDbClientOptionsFactoryBean(final AbstractMongoInstanceProperties mongo) {
    try {
        final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
        bean.setWriteConcern(WriteConcern.valueOf(mongo.getWriteConcern()));
        bean.setHeartbeatConnectTimeout(Long.valueOf(mongo.getTimeout()).intValue());
        bean.setHeartbeatSocketTimeout(Long.valueOf(mongo.getTimeout()).intValue());
        bean.setMaxConnectionLifeTime(mongo.getConns().getLifetime());
        bean.setSocketKeepAlive(mongo.isSocketKeepAlive());
        bean.setMaxConnectionIdleTime(Long.valueOf(mongo.getIdleTimeout()).intValue());
        bean.setConnectionsPerHost(mongo.getConns().getPerHost());
        bean.setSocketTimeout(Long.valueOf(mongo.getTimeout()).intValue());
        bean.setConnectTimeout(Long.valueOf(mongo.getTimeout()).intValue());
        bean.afterPropertiesSet();
        return bean;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) MongoClientOptionsFactoryBean(org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean) BeanCreationException(org.springframework.beans.factory.BeanCreationException)

Example 2 with BeanCreationException

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

the class MockitoPostProcessor method inject.

private void inject(Field field, Object target, String beanName, Definition definition) {
    try {
        field.setAccessible(true);
        Assert.state(ReflectionUtils.getField(field, target) == null, "The field " + field + " cannot have an existing value");
        Object bean = this.beanFactory.getBean(beanName, field.getType());
        if (definition.isProxyTargetAware() && isAopProxy(bean)) {
            MockitoAopProxyTargetInterceptor.applyTo(bean);
        }
        ReflectionUtils.setField(field, target, bean);
    } catch (Throwable ex) {
        throw new BeanCreationException("Could not inject field: " + field, ex);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException)

Example 3 with BeanCreationException

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

the class BindFailureAnalyzerTests method performAnalysis.

private FailureAnalysis performAnalysis(Class<?> configuration) {
    BeanCreationException failure = createFailure(configuration);
    assertThat(failure).isNotNull();
    return new BindFailureAnalyzer().analyze(failure);
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException)

Example 4 with BeanCreationException

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

the class ConfigurationPropertiesBindingPostProcessorTests method unknownFieldFailureMessageContainsDetailsOfPropertyOrigin.

@Test
public void unknownFieldFailureMessageContainsDetailsOfPropertyOrigin() {
    this.context = new AnnotationConfigApplicationContext();
    TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "com.example.baz=spam");
    this.context.register(TestConfiguration.class);
    try {
        this.context.refresh();
        fail("Expected exception");
    } catch (BeanCreationException ex) {
        RelaxedBindingNotWritablePropertyException bex = (RelaxedBindingNotWritablePropertyException) ex.getRootCause();
        assertThat(bex.getMessage()).startsWith("Failed to bind 'com.example.baz' from '" + TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME + "' to 'baz' " + "property on '" + TestConfiguration.class.getName());
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) RelaxedBindingNotWritablePropertyException(org.springframework.boot.bind.RelaxedBindingNotWritablePropertyException) Test(org.junit.Test)

Example 5 with BeanCreationException

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

the class AbstractBeanFactory method doGetBean.

/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * @param name the name of the bean to retrieve
	 * @param requiredType the required type of the bean to retrieve
	 * @param args arguments to use when creating a bean instance using explicit arguments
	 * (only applied when creating a new instance as opposed to retrieving an existing one)
	 * @param typeCheckOnly whether the instance is obtained for a type check,
	 * not for actual use
	 * @return an instance of the bean
	 * @throws BeansException if the bean could not be created
	 */
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
    final String beanName = transformedBeanName(name);
    Object bean;
    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isDebugEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
            } else {
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    } else {
        // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            } else {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }
        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }
        try {
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            // Guarantee initialization of beans that the current bean depends on.
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    registerDependentBean(dep, beanName);
                    getBean(dep);
                }
            }
            // Create bean instance.
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {

                    @Override
                    public Object getObject() throws BeansException {
                        try {
                            return createBean(beanName, mbd, args);
                        } catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            } else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                } finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {

                        @Override
                        public Object getObject() throws BeansException {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            } finally {
                                afterPrototypeCreation(beanName);
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                } catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex);
                }
            }
        } catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }
    // Check if required type matches the type of the actual bean instance.
    if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
        try {
            return getTypeConverter().convertIfNecessary(bean, requiredType);
        } catch (TypeMismatchException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) TypeMismatchException(org.springframework.beans.TypeMismatchException) BeanCurrentlyInCreationException(org.springframework.beans.factory.BeanCurrentlyInCreationException) BeanNotOfRequiredTypeException(org.springframework.beans.factory.BeanNotOfRequiredTypeException) ObjectFactory(org.springframework.beans.factory.ObjectFactory) Scope(org.springframework.beans.factory.config.Scope) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) BeansException(org.springframework.beans.BeansException)

Aggregations

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