Search in sources :

Example 1 with TypeMismatchException

use of org.springframework.beans.TypeMismatchException 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 TypeMismatchException

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

the class DefaultHandlerExceptionResolverTests method handleTypeMismatch.

@Test
public void handleTypeMismatch() {
    TypeMismatchException ex = new TypeMismatchException("foo", String.class);
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertThat(mav).as("No ModelAndView returned").isNotNull();
    assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
    assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
Also used : TypeMismatchException(org.springframework.beans.TypeMismatchException) ModelAndView(org.springframework.web.servlet.ModelAndView) Test(org.junit.jupiter.api.Test)

Example 3 with TypeMismatchException

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

the class ResponseStatusExceptionResolverTests method nestedException.

// SPR-12903
@Test
public void nestedException() throws Exception {
    Exception cause = new StatusCodeAndReasonMessageException();
    TypeMismatchException ex = new TypeMismatchException("value", ITestBean.class, cause);
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertResolved(mav, 410, "gone.reason");
}
Also used : TypeMismatchException(org.springframework.beans.TypeMismatchException) ModelAndView(org.springframework.web.servlet.ModelAndView) ResponseStatusException(org.springframework.web.server.ResponseStatusException) TypeMismatchException(org.springframework.beans.TypeMismatchException) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) Test(org.junit.jupiter.api.Test)

Example 4 with TypeMismatchException

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

the class ResponseEntityExceptionHandlerTests method typeMismatch.

@Test
public void typeMismatch() {
    Exception ex = new TypeMismatchException("foo", String.class);
    testException(ex);
}
Also used : TypeMismatchException(org.springframework.beans.TypeMismatchException) MissingPathVariableException(org.springframework.web.bind.MissingPathVariableException) ServletException(jakarta.servlet.ServletException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) NoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException) MissingServletRequestPartException(org.springframework.web.multipart.support.MissingServletRequestPartException) BindException(org.springframework.validation.BindException) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) AsyncRequestTimeoutException(org.springframework.web.context.request.async.AsyncRequestTimeoutException) MissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ServletRequestBindingException(org.springframework.web.bind.ServletRequestBindingException) TypeMismatchException(org.springframework.beans.TypeMismatchException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) Test(org.junit.jupiter.api.Test)

Example 5 with TypeMismatchException

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

the class MarshallingMessageConverter method convertFromInternal.

@Override
@Nullable
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
    Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
    try {
        Source source = getSource(message.getPayload());
        Object result = this.unmarshaller.unmarshal(source);
        if (!targetClass.isInstance(result)) {
            throw new TypeMismatchException(result, targetClass);
        }
        return result;
    } catch (Exception ex) {
        throw new MessageConversionException(message, "Could not unmarshal XML: " + ex.getMessage(), ex);
    }
}
Also used : TypeMismatchException(org.springframework.beans.TypeMismatchException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) TypeMismatchException(org.springframework.beans.TypeMismatchException) Nullable(org.springframework.lang.Nullable)

Aggregations

TypeMismatchException (org.springframework.beans.TypeMismatchException)15 HashSet (java.util.HashSet)4 Test (org.junit.jupiter.api.Test)4 MethodParameter (org.springframework.core.MethodParameter)4 TypeConverter (org.springframework.beans.TypeConverter)3 Nullable (org.springframework.lang.Nullable)3 BindException (org.springframework.validation.BindException)3 BeansException (org.springframework.beans.BeansException)2 ConversionNotSupportedException (org.springframework.beans.ConversionNotSupportedException)2 NotWritablePropertyException (org.springframework.beans.NotWritablePropertyException)2 InjectionPoint (org.springframework.beans.factory.InjectionPoint)2 UnsatisfiedDependencyException (org.springframework.beans.factory.UnsatisfiedDependencyException)2 WebDataBinder (org.springframework.web.bind.WebDataBinder)2 ModelAndView (org.springframework.web.servlet.ModelAndView)2 EntityNotFoundException (ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException)1 InvalidPropertyException (ca.corefacility.bioinformatics.irida.exceptions.InvalidPropertyException)1 AccessDeniedException (com.baidu.dsp.common.exception.AccessDeniedException)1 DocumentNotFoundException (com.baidu.dsp.common.exception.DocumentNotFoundException)1 FieldException (com.baidu.dsp.common.exception.FieldException)1 GlobalExceptionAware (com.baidu.dsp.common.exception.base.GlobalExceptionAware)1