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

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

Introduction

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

Prototype

public BeanDefinitionStoreException(String msg) 

Source Link

Document

Create a new BeanDefinitionStoreException.

Usage

From source file:org.springframework.aop.target.AbstractPrototypeBasedTargetSource.java

/**
 * Set the owning BeanFactory. We need to save a reference so that we can
 * use the getBean() method on every invocation.
 *///w  w  w.jav a 2 s.  co  m
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    this.owningBeanFactory = beanFactory;

    // check whether the target bean is defined as prototype
    if (this.owningBeanFactory.isSingleton(this.targetBeanName)) {
        throw new BeanDefinitionStoreException(
                "Cannot use PrototypeTargetSource against a singleton bean: instances would not be independent");
    }

    // determine type of the target bean
    if (beanFactory instanceof ConfigurableListableBeanFactory) {
        this.targetClass = ((ConfigurableListableBeanFactory) beanFactory)
                .getBeanDefinition(this.targetBeanName).getBeanClass();
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Getting bean with name '" + this.targetBeanName + "' to find class");
        }
        this.targetClass = this.owningBeanFactory.getBean(this.targetBeanName).getClass();
    }
}

From source file:org.springframework.aop.target.AbstractPrototypeTargetSource.java

/**
 * Set the owning BeanFactory. We need to save a reference so that we can
 * use the getBean() method on every invocation.
 *//*from w  w w  .java 2 s .  c  o m*/
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    this.owningBeanFactory = beanFactory;
    if (this.owningBeanFactory.isSingleton(this.targetBeanName)) {
        throw new BeanDefinitionStoreException(
                "Cannot use PrototypeTargetSource against a Singleton bean; instances would not be independent");
    }
    logger.info("Getting bean with name '" + targetBeanName + "' to find class");
    this.targetClass = owningBeanFactory.getBean(targetBeanName).getClass();
}

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

/**
 * Load bean definitions from the specified resource location.
 * <p>The location can also be a location pattern, provided that the
 * ResourceLoader of this bean definition reader is a ResourcePatternResolver.
 * @param location the resource location, to be loaded with the ResourceLoader
 * (or ResourcePatternResolver) of this bean definition reader
 * @param actualResources a Set to be filled with the actual Resource objects
 * that have been resolved during the loading process. May be {@code null}
 * to indicate that the caller is not interested in those Resource objects.
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 * @see #getResourceLoader()/*w  w w  .  ja  va2  s.  co  m*/
 * @see #loadBeanDefinitions(org.springframework.core.io.Resource)
 * @see #loadBeanDefinitions(org.springframework.core.io.Resource[])
 */
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources)
        throws BeanDefinitionStoreException {
    ResourceLoader resourceLoader = getResourceLoader();
    if (resourceLoader == null) {
        throw new BeanDefinitionStoreException(
                "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
    }

    if (resourceLoader instanceof ResourcePatternResolver) {
        // Resource pattern matching available.
        try {
            Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
            int loadCount = loadBeanDefinitions(resources);
            if (actualResources != null) {
                for (Resource resource : resources) {
                    actualResources.add(resource);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
            }
            return loadCount;
        } catch (IOException ex) {
            throw new BeanDefinitionStoreException(
                    "Could not resolve bean definition resource pattern [" + location + "]", ex);
        }
    } else {
        // Can only load single resources by absolute URL.
        Resource resource = resourceLoader.getResource(location);
        int loadCount = loadBeanDefinitions(resource);
        if (actualResources != null) {
            actualResources.add(resource);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
        }
        return loadCount;
    }
}

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

public void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException {
    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.hasText(alias, "Alias must not be empty");
    if (!alias.equals(beanName)) {
        // Only actually register the alias if it is not equal to the bean name itself.
        if (logger.isDebugEnabled()) {
            logger.debug("Registering alias '" + alias + "' for bean with name '" + beanName + "'");
        }// w  ww  .  j a v  a2 s . c o  m
        synchronized (this.aliasMap) {
            Object registeredName = this.aliasMap.get(alias);
            if (registeredName != null && !registeredName.equals(beanName)) {
                throw new BeanDefinitionStoreException("Cannot register alias '" + alias + "' for bean name '"
                        + beanName + "': It's already registered for bean name '" + registeredName + "'.");
            }
            this.aliasMap.put(alias, beanName);
        }
    }
}

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

public void registerSingleton(String beanName, Object singletonObject) throws BeanDefinitionStoreException {
    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(singletonObject, "Singleton object must not be null");
    synchronized (this.singletonCache) {
        Object oldObject = this.singletonCache.get(beanName);
        if (oldObject != null) {
            throw new BeanDefinitionStoreException("Could not register object [" + singletonObject
                    + "] under bean name '" + beanName + "': there's already object [" + oldObject + " bound");
        }/*w  w w .  jav a  2s . c o  m*/
        addSingleton(beanName, singletonObject);
    }
}

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/*  www.  j  a  v a 2s  .c o  m*/
 * @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");
        }
    }
}

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

public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
        Object factoryBean, Method factoryMethod, Object[] args) {

    try {/*from  www. j  a  v  a 2 s . co  m*/
        // It's a static method if the target is null.
        if (!Modifier.isPublic(factoryMethod.getModifiers())
                || !Modifier.isPublic(factoryMethod.getDeclaringClass().getModifiers())) {
            factoryMethod.setAccessible(true);
        }
        return factoryMethod.invoke(factoryBean, args);
    } catch (IllegalArgumentException ex) {
        throw new BeanDefinitionStoreException("Illegal arguments to factory method [" + factoryMethod + "]; "
                + "args: " + StringUtils.arrayToCommaDelimitedString(args));
    } catch (IllegalAccessException ex) {
        throw new BeanDefinitionStoreException(
                "Cannot access factory method [" + factoryMethod + "]; is it public?");
    } catch (InvocationTargetException ex) {
        String msg = "Factory method [" + factoryMethod + "] threw exception";
        // We want to log this one, as it may be a config error:
        // the method may match, but may have been given incorrect arguments.
        logger.warn(msg, ex.getTargetException());
        throw new BeanDefinitionStoreException(msg, ex.getTargetException());
    }
}

From source file:org.springframework.context.annotation.ConfigurationClassPostProcessor.java

/**
 * Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
 * any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
 * Candidate status is determined by BeanDefinition attribute metadata.
 * @see ConfigurationClassEnhancer// w ww  . j a  v a  2 s .c  o  m
 */
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
    Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
            if (!(beanDef instanceof AbstractBeanDefinition)) {
                throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '"
                        + beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
            } else if (logger.isWarnEnabled() && beanFactory.containsSingleton(beanName)) {
                logger.warn("Cannot enhance @Configuration bean definition '" + beanName
                        + "' since its singleton instance has been created too early. The typical cause "
                        + "is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor "
                        + "return type: Consider declaring such methods as 'static'.");
            }
            configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
        }
    }
    if (configBeanDefs.isEmpty()) {
        // nothing to enhance -> return immediately
        return;
    }

    ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
    for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
        AbstractBeanDefinition beanDef = entry.getValue();
        // If a @Configuration class gets proxied, always proxy the target class
        beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
        try {
            // Set enhanced subclass of the user-specified bean class
            Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
            if (configClass != null) {
                Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
                if (configClass != enhancedClass) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format(
                                "Replacing bean definition '%s' existing class '%s' with "
                                        + "enhanced class '%s'",
                                entry.getKey(), configClass.getName(), enhancedClass.getName()));
                    }
                    beanDef.setBeanClass(enhancedClass);
                }
            }
        } catch (Throwable ex) {
            throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(),
                    ex);
        }
    }
}

From source file:org.springframework.integration.aws.sqs.config.AmazonSQSInboundChannelAdapterParser.java

@Override
protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) {
    String awsCredentials = registerAmazonWSCredentials(element, parserContext);
    //Mandated at xsd level, so has to be present
    String sqsQueue = element.getAttribute(SQS_QUEUE);
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(AmazonSQSMessageSource.class)
            .addConstructorArgReference(awsCredentials).addConstructorArgValue(sqsQueue);
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, IS_TRANSACTIONAL);
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, MAX_REDELIVERY_ATTEMPTS);
    IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, SQS_OPERATIONS);
    String messageTransformerRef = element.getAttribute(MESSAGE_TRANSFORMER);
    boolean hasMessageTransformerRef = StringUtils.hasText(messageTransformerRef);

    boolean hasSnsHeaderPrefix = false;
    String snsNotificationAttribute = element.getAttribute(CHECK_SNS_NOTIFICATION);
    boolean checkSnsNotification = StringUtils.hasText(snsNotificationAttribute);
    String snsHeaderPrefix = null;
    if (checkSnsNotification) {
        snsHeaderPrefix = element.getAttribute(SNS_HEADER_PREFIX);
        hasSnsHeaderPrefix = StringUtils.hasText(snsHeaderPrefix);
    }//from w  w  w  .j a  v  a2  s.c  om

    if (!element.hasAttribute(SQS_OPERATIONS)) {
        BeanDefinitionBuilder sqsOperationsBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(AmazonSQSOperationsImpl.class)
                .addConstructorArgReference(awsCredentials);
        if (hasMessageTransformerRef) {
            sqsOperationsBuilder.addPropertyReference("messageTransformer", messageTransformerRef);
        }

        if (checkSnsNotification) {
            sqsOperationsBuilder.addPropertyValue("checkSnsNotification", true);
            if (hasSnsHeaderPrefix) {
                sqsOperationsBuilder.addPropertyValue("snsHeaderPrefix", snsHeaderPrefix);
            }
        }

        //sqs_operations attribute not defined, register the default one
        String operationsBean = BeanDefinitionReaderUtils.registerWithGeneratedName(
                sqsOperationsBuilder.getBeanDefinition(), parserContext.getRegistry());
        builder.addPropertyReference("sqsOperations", operationsBean);
    } else {
        if (hasMessageTransformerRef) {
            //This means, we have a reference to both sqs operations and message transformer provided
            throw new BeanDefinitionStoreException(
                    "Both the attributes,  \"sqs-operations\" and \"message-transformer\" are "
                            + "not supported together. Consider injecting the messageTransformer in the sqsOperation's bean definition"
                            + " and provide \"sqs-operations\" attribute only");
        }
        if (checkSnsNotification) {
            logger.warn("check-sns-notification and sns-header-prefix attributes are supported"
                    + " only when default implementation of sqs operations is used");
        }

    }
    return builder.getBeanDefinition();
}

From source file:org.springframework.integration.comet.core.CometMessagingServices.java

public void afterPropertiesSet() throws Exception {
    if (!StringUtils.hasText(endpointUrl))
        throw new BeanDefinitionStoreException("attributes \"endpointUrl\" is mandatory");

    if (transport instanceof AbstractCometMessagingTransport) {
        ((AbstractCometMessagingTransport) transport).initializeTransport();
    }/*from w  ww  .  j a va  2s. c om*/

    if (transformer == null)
        throw new BeanDefinitionStoreException("A Transformer is required to convert the messages"
                + " from a user provided type to a CometMessage and from CometMessage to the user message class");

    if (transport == null)
        throw new BeanDefinitionStoreException("A Transport implementation is madatory or sending"
                + " the comet message over to the endpoint");
}