Example usage for org.springframework.beans.factory BeanNotOfRequiredTypeException BeanNotOfRequiredTypeException

List of usage examples for org.springframework.beans.factory BeanNotOfRequiredTypeException BeanNotOfRequiredTypeException

Introduction

In this page you can find the example usage for org.springframework.beans.factory BeanNotOfRequiredTypeException BeanNotOfRequiredTypeException.

Prototype

public BeanNotOfRequiredTypeException(String beanName, Class<?> requiredType, Class<?> actualType) 

Source Link

Document

Create a new BeanNotOfRequiredTypeException.

Usage

From source file:de.blizzy.documentr.markdown.macro.MacroBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    Macro annotation = bean.getClass().getAnnotation(Macro.class);
    if (annotation != null) {
        if (StringUtils.isBlank(annotation.name())) {
            throw new BeanDefinitionValidationException("no macro name specified in @" + //$NON-NLS-1$
                    Macro.class.getSimpleName() + " annotation for bean: " + beanName); //$NON-NLS-1$
        }/*from  w  w w .  java2 s .  co  m*/

        if (!(bean instanceof IMacro)) {
            if (bean instanceof ISimpleMacro) {
                return createMacro((ISimpleMacro) bean, annotation);
            } else if (bean instanceof IMacroRunnable) {
                @SuppressWarnings("unchecked")
                Class<? extends IMacroRunnable> clazz = (Class<? extends IMacroRunnable>) bean.getClass();
                return createMacro(clazz, annotation);
            } else {
                throw new BeanNotOfRequiredTypeException(beanName, ISimpleMacro.class, bean.getClass());
            }
        } else {
            throw new BeanNotOfRequiredTypeException(beanName, ISimpleMacro.class, bean.getClass());
        }
    } else {
        return bean;
    }
}

From source file:com.griddynamics.banshun.ExportTargetSource.java

public Object getTarget() throws BeansException {
    Object localTarget = target.get();

    if (localTarget == null) {
        // verify if declared service interface is compatible with the real bean type
        Class<?> beanClass = beanFactory.getType(beanName);
        if (!serviceInterface.isAssignableFrom(beanClass)) {
            throw new BeanNotOfRequiredTypeException(beanName, serviceInterface, beanClass);
        }//from  ww  w .  j av  a2 s .c o m

        if (target.compareAndSet(null, localTarget = beanFactory.getBean(beanName))) {
            return localTarget;

        } else {
            log.debug("Redundant initialization of ExportTargetSource for bean '{}' caused by"
                    + "concurrency has been detected.", beanName);
            return target.get();
        }
    }
    return localTarget;
}

From source file:org.ops4j.pax.wicket.test.spring.ApplicationContextMock.java

public Object getBean(String name, Class requiredType) throws BeansException {
    Object bean = getBean(name);/*from   www.  j a v  a 2s . com*/
    if (!requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return bean;
}

From source file:com.griddynamics.banshun.LookupTargetSource.java

public Object getTarget() throws BeansException {
    Object localTarget = target.get();

    if (localTarget == null) {
        if (!rootContext.containsBean(exportProxyName)) {
            throw new NoSuchBeanDefinitionException(exportProxyName, String
                    .format("can't find export declaration for lookup(%s, %s)", serviceName, serviceInterface));
        }//from w w  w.  ja v  a  2 s .  com
        ExportTargetSource exportProxy = rootContext.getBean(exportProxyName, ExportTargetSource.class);

        // verify if service interfaces on both sides are compatible
        if (!serviceInterface.isAssignableFrom(exportProxy.getTargetClass())) {
            throw new BeanNotOfRequiredTypeException(serviceName, serviceInterface,
                    exportProxy.getTargetClass());
        }

        if (target.compareAndSet(null, localTarget = exportProxy.getTarget())) {
            return localTarget;

        } else {
            // log potentially redundant instance initialization
            log.warn("Bean {} was created earlier", serviceName);
            return target.get();
        }
    }
    return localTarget;
}

From source file:com.predic8.membrane.annot.parser.BlueprintSimulatedSpringApplicationContext.java

@SuppressWarnings("unchecked")
@Override/*from   w ww .j  ava  2  s  .co  m*/
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    Object bean = getBean(name);
    if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return (T) bean;
}

From source file:org.jboss.spring.facade.ControllerBeanFactory.java

/**
 * Get exact bean./*from w  w  w.j  av  a2s.c o m*/
 *
 * @param name  the bean name
 * @param clazz the expected class
 * @param <T>   the exact type
 * @return exact bean
 * @throws BeansException for any error
 */
protected <T> T getBeanWithType(String name, Class<T> clazz) throws BeansException {
    Object result = getBean(name);
    if (!clazz.isInstance(result)) {
        throw new BeanNotOfRequiredTypeException(name, clazz, result.getClass());
    }

    return clazz.cast(result);
}

From source file:net.mojodna.sprout.Sprout.java

public final void setBeanFactory(final BeanFactory factory) throws BeansException {
    if (!factory.isSingleton(beanName)) {
        log.warn(getClass().getName() + " must be defined with singleton=\"true\" in order to self-register.");
        return;//from ww w  . j  a v  a2s.  c om
    }

    final String pkgName = getClass().getPackage().getName();
    final String path = pkgName.substring(pkgName.indexOf(PACKAGE_DELIMITER) + PACKAGE_DELIMITER.length())
            .replace('.', '/') + "/";

    if (factory instanceof AbstractBeanFactory) {
        final AbstractBeanFactory dlbf = (AbstractBeanFactory) factory;

        final Collection<Method> methods = SproutUtils.getDeclaredMethods(getClass(), Sprout.class);

        // register beans for each url
        log.debug("Registering paths...");
        for (final Iterator<Method> i = methods.iterator(); i.hasNext();) {
            final Method method = i.next();
            String name = method.getName();
            if (Modifier.isPublic(method.getModifiers())
                    && method.getReturnType().equals(ActionForward.class)) {
                if (name.equals("publick"))
                    name = "public";
                final String url = path + name.replaceAll("([A-Z])", "_$1").toLowerCase();
                log.debug(url);
                if (!ArrayUtils.contains(dlbf.getAliases(beanName), url))
                    dlbf.registerAlias(beanName, url);
            }
        }
    } else {
        log.warn("Unable to self-register; factory bean was of an unsupported type.");
        throw new BeanNotOfRequiredTypeException(beanName, AbstractBeanFactory.class, factory.getClass());
    }
}

From source file:org.springframework.beans.factory.support.AbstractBeanFactory.java

/**
 * 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 if creating a prototype using explicit arguments to a
 * static factory method. It is invalid to use a non-null args value in any other case.
 * @return an instance of the bean//from  w ww  . ja v  a2 s .c  o  m
 * @throws BeansException if the bean could not be created
 */
public Object getBean(String name, Class requiredType, Object[] args) throws BeansException {
    String beanName = transformedBeanName(name);
    Object bean = null;

    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = null;
    synchronized (this.singletonCache) {
        sharedInstance = this.singletonCache.get(beanName);
    }
    if (sharedInstance != null) {
        if (isSingletonCurrentlyInCreation(beanName)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName
                        + "' that is not fully initialized yet - a consequence of a circular reference");
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        bean = getObjectForSharedInstance(name, sharedInstance);
    }

    else {
        // Fail if we're already creating this singleton instance:
        // We're assumably within a circular reference.
        if (isSingletonCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // Check if bean definition exists in this factory.
        if (getParentBeanFactory() != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            if (getParentBeanFactory() instanceof AbstractBeanFactory) {
                // Delegation to parent with args only possible for AbstractBeanFactory.
                return ((AbstractBeanFactory) getParentBeanFactory()).getBean(name, requiredType, args);
            } else if (args == null) {
                // No args -> delegate to standard getBean method.
                return getParentBeanFactory().getBean(name, requiredType);
            } else {
                throw new NoSuchBeanDefinitionException(beanName,
                        "Cannot delegate to parent BeanFactory because it does not supported passed-in arguments");
            }
        }

        RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(beanName, false);
        checkMergedBeanDefinition(mergedBeanDefinition, beanName, requiredType, args);

        // Create bean instance.
        if (mergedBeanDefinition.isSingleton()) {
            synchronized (this.singletonCache) {
                // Re-check singleton cache within synchronized block.
                sharedInstance = this.singletonCache.get(beanName);
                if (sharedInstance == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
                    }
                    this.currentlyInCreation.add(beanName);
                    try {
                        sharedInstance = createBean(beanName, mergedBeanDefinition, args);
                        addSingleton(beanName, sharedInstance);
                    } 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.
                        destroyDisposableBean(beanName);
                        throw ex;
                    } finally {
                        this.currentlyInCreation.remove(beanName);
                    }
                }
            }
            bean = getObjectForSharedInstance(name, sharedInstance);
        } else {
            // It's a prototype -> create a new instance.
            bean = createBean(beanName, mergedBeanDefinition, args);
        }
    }

    // Check if required type matches the type of the actual bean instance.
    if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return bean;
}

From source file:org.springframework.beans.factory.support.AbstractBeanFactory.java

/**
 * Check the given merged bean definition,
 * potentially throwing validation exceptions.
 * @param mergedBeanDefinition the bean definition to check
 * @param beanName the name of the bean// w  ww  .  j a  va2  s  .  com
 * @param requiredType the required type of the bean
 * @param args the arguments for bean creation, if any
 * @throws BeansException in case of validation failure
 */
protected void checkMergedBeanDefinition(RootBeanDefinition mergedBeanDefinition, String beanName,
        Class requiredType, Object[] args) throws BeansException {

    // check if bean definition is not abstract
    if (mergedBeanDefinition.isAbstract()) {
        throw new BeanIsAbstractException(beanName);
    }

    // Check if required type can match according to the bean definition.
    // This is only possible at this early stage for conventional beans!
    if (mergedBeanDefinition.hasBeanClass()) {
        Class beanClass = mergedBeanDefinition.getBeanClass();
        if (requiredType != null && mergedBeanDefinition.getFactoryMethodName() == null
                && !FactoryBean.class.isAssignableFrom(beanClass)
                && !requiredType.isAssignableFrom(beanClass)) {
            throw new BeanNotOfRequiredTypeException(beanName, requiredType, beanClass);
        }
    }

    // Check validity of the usage of the args parameter. This can
    // only be used for prototypes constructed via a factory method.
    if (args != null) {
        if (mergedBeanDefinition.isSingleton()) {
            throw new BeanDefinitionStoreException(
                    "Cannot specify arguments in the getBean() method when referring to a singleton bean definition");
        } else if (mergedBeanDefinition.getFactoryMethodName() == null) {
            throw new BeanDefinitionStoreException(
                    "Can only specify arguments in the getBean() method in conjunction with a factory method");
        }
    }
}