Search in sources :

Example 1 with BeanNotOfRequiredTypeException

use of org.springframework.beans.factory.BeanNotOfRequiredTypeException 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)

Example 2 with BeanNotOfRequiredTypeException

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

the class BeanFactoryDataSourceLookupTests method testLookupWhereBeanFactoryYieldsNonDataSourceType.

@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
    final BeanFactory beanFactory = mock(BeanFactory.class);
    given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class));
    try {
        BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
        lookup.getDataSource(DATASOURCE_BEAN_NAME);
        fail("should have thrown DataSourceLookupFailureException");
    } catch (DataSourceLookupFailureException ex) {
    /* expected */
    }
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) BeanNotOfRequiredTypeException(org.springframework.beans.factory.BeanNotOfRequiredTypeException) DataSource(javax.sql.DataSource) Test(org.junit.Test)

Example 3 with BeanNotOfRequiredTypeException

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

the class DefaultListableBeanFactory method checkBeanNotOfRequiredType.

/**
	 * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable,
	 * i.e. if the target type of the bean would match but an exposed proxy doesn't.
	 */
private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) {
    for (String beanName : this.beanDefinitionNames) {
        RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        Class<?> targetType = mbd.getTargetType();
        if (targetType != null && type.isAssignableFrom(targetType) && isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
            // Probably a proxy interfering with target type match -> throw meaningful exception.
            Object beanInstance = getSingleton(beanName, false);
            Class<?> beanType = (beanInstance != null ? beanInstance.getClass() : predictBeanType(beanName, mbd));
            if (!type.isAssignableFrom((beanType))) {
                throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
            }
        }
    }
    BeanFactory parent = getParentBeanFactory();
    if (parent instanceof DefaultListableBeanFactory) {
        ((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
    }
}
Also used : ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) AutowireCapableBeanFactory(org.springframework.beans.factory.config.AutowireCapableBeanFactory) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) BeanNotOfRequiredTypeException(org.springframework.beans.factory.BeanNotOfRequiredTypeException)

Example 4 with BeanNotOfRequiredTypeException

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

the class EnableAsyncTests method properExceptionForResolvedProxyDependencyMismatch.

@Test
public void properExceptionForResolvedProxyDependencyMismatch() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AsyncConfig.class, AsyncBeanUser.class, AsyncBeanWithInterface.class);
    try {
        ctx.refresh();
        fail("Should have thrown UnsatisfiedDependencyException");
    } catch (UnsatisfiedDependencyException ex) {
        ex.printStackTrace();
        assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
    }
}
Also used : AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) BeanNotOfRequiredTypeException(org.springframework.beans.factory.BeanNotOfRequiredTypeException) Test(org.junit.Test)

Example 5 with BeanNotOfRequiredTypeException

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

the class EnableAsyncTests method properExceptionForExistingProxyDependencyMismatch.

@Test
public void properExceptionForExistingProxyDependencyMismatch() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AsyncConfig.class, AsyncBeanWithInterface.class, AsyncBeanUser.class);
    try {
        ctx.refresh();
        fail("Should have thrown UnsatisfiedDependencyException");
    } catch (UnsatisfiedDependencyException ex) {
        ex.printStackTrace();
        assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
    }
}
Also used : AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) BeanNotOfRequiredTypeException(org.springframework.beans.factory.BeanNotOfRequiredTypeException) Test(org.junit.Test)

Aggregations

BeanNotOfRequiredTypeException (org.springframework.beans.factory.BeanNotOfRequiredTypeException)5 Test (org.junit.Test)3 BeanFactory (org.springframework.beans.factory.BeanFactory)3 UnsatisfiedDependencyException (org.springframework.beans.factory.UnsatisfiedDependencyException)2 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)2 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)2 DataSource (javax.sql.DataSource)1 BeansException (org.springframework.beans.BeansException)1 TypeMismatchException (org.springframework.beans.TypeMismatchException)1 BeanCreationException (org.springframework.beans.factory.BeanCreationException)1 BeanCurrentlyInCreationException (org.springframework.beans.factory.BeanCurrentlyInCreationException)1 ObjectFactory (org.springframework.beans.factory.ObjectFactory)1 AutowireCapableBeanFactory (org.springframework.beans.factory.config.AutowireCapableBeanFactory)1 ConfigurableListableBeanFactory (org.springframework.beans.factory.config.ConfigurableListableBeanFactory)1 Scope (org.springframework.beans.factory.config.Scope)1