Example usage for org.springframework.beans.factory.parsing BeanComponentDefinition BeanComponentDefinition

List of usage examples for org.springframework.beans.factory.parsing BeanComponentDefinition BeanComponentDefinition

Introduction

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

Prototype

public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName) 

Source Link

Document

Create a new BeanComponentDefinition for the given bean.

Usage

From source file:org.apache.camel.spring.handler.CamelNamespaceHandler.java

private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext,
        String contextId) {/*from   w ww  .ja v a2 s. c o m*/
    // it is a bit cumbersome to work with the spring bean definition parser
    // as we kinda need to eagerly register the bean definition on the parser context
    // and then later we might find out that we should not have done that in case we have multiple camel contexts
    // that would have a id clash by auto registering the same bean definition with the same id such as a producer template

    // see if we have already auto registered this id
    BeanDefinition existing = autoRegisterMap.get(id);
    if (existing == null) {
        // no then add it to the map and register it
        autoRegisterMap.put(id, definition);
        parserContext.registerComponent(new BeanComponentDefinition(definition, id));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Registered default: " + definition.getBeanClassName() + " with id: " + id
                    + " on camel context: " + contextId);
        }
    } else {
        // ups we have already registered it before with same id, but on another camel context
        // this is not good so we need to remove all traces of this auto registering.
        // end user must manually add the needed XML elements and provide unique ids access all camel context himself.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unregistered default: " + definition.getBeanClassName() + " with id: " + id
                    + " as we have multiple camel contexts and they must use unique ids."
                    + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts");
        }

        parserContext.getRegistry().removeBeanDefinition(id);
    }
}

From source file:org.apache.camel.spring.handler.CamelNamespaceHandler.java

private void registerEndpoint(Element childElement, ParserContext parserContext, String contextId) {
    String id = childElement.getAttribute("id");
    // must have an id to be registered
    if (ObjectHelper.isNotEmpty(id)) {
        BeanDefinition definition = endpointParser.parse(childElement, parserContext);
        definition.getPropertyValues().addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
        // Need to add this dependency of CamelContext for Spring 3.0
        try {//w ww .  java 2 s .  co m
            Method method = definition.getClass().getMethod("setDependsOn", String[].class);
            method.invoke(definition, (Object) new String[] { contextId });
        } catch (Exception e) {
            // Do nothing here
        }
        parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id));
    }
}

From source file:org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser.java

/**
 * Registers a generic repository factory bean for a bean with the given name and the provided configuration context.
 * //w  w  w .j av  a2s . co  m
 * @param parser
 * @param name
 * @param context
 */
private void registerGenericRepositoryFactoryBean(ParserContext parser, T context) {

    try {

        Object beanSource = parser.extractSource(context.getSource());

        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .rootBeanDefinition(context.getRepositoryFactoryBeanClassName());

        builder.addPropertyValue("repositoryInterface", context.getInterfaceName());
        builder.addPropertyValue("queryLookupStrategyKey", context.getQueryLookupStrategyKey());
        builder.addPropertyValue("namedQueries",
                new NamedQueriesBeanDefinitionParser(context.getNamedQueriesLocation())
                        .parse(context.getSource(), parser));

        String customImplementationBeanName = registerCustomImplementation(context, parser, beanSource);

        if (customImplementationBeanName != null) {
            builder.addPropertyReference("customImplementation", customImplementationBeanName);
        }

        postProcessBeanDefinition(context, builder, parser.getRegistry(), beanSource);

        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
        beanDefinition.setSource(beanSource);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Registering repository: " + context.getBeanId() + " - Interface: "
                    + context.getInterfaceName() + " - Factory: " + context.getRepositoryFactoryBeanClassName()
                    + ", - Custom implementation: " + customImplementationBeanName);
        }

        BeanComponentDefinition definition = new BeanComponentDefinition(beanDefinition, context.getBeanId());
        parser.registerBeanComponent(definition);
    } catch (RuntimeException e) {
        handleError(e, context.getSource(), parser.getReaderContext());
    }
}

From source file:org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser.java

/**
 * Registers a possibly available custom repository implementation on the repository bean. Tries to find an already
 * registered bean to reference or tries to detect a custom implementation itself.
 * /*from ww  w  . java 2  s. c om*/
 * @param config
 * @param parser
 * @param source
 * @return the bean name of the custom implementation or {@code null} if none available
 */
private String registerCustomImplementation(T config, ParserContext parser, Object source) {

    String beanName = config.getImplementationBeanName();

    // Already a bean configured?
    if (parser.getRegistry().containsBeanDefinition(beanName)) {
        return beanName;
    }

    // Autodetect implementation
    if (config.autodetectCustomImplementation()) {

        AbstractBeanDefinition beanDefinition = detectCustomImplementation(config, parser);

        if (null == beanDefinition) {
            return null;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Registering custom repository implementation: " + config.getImplementationBeanName()
                    + " " + beanDefinition.getBeanClassName());
        }

        beanDefinition.setSource(source);
        parser.registerBeanComponent(new BeanComponentDefinition(beanDefinition, beanName));

    } else {
        beanName = config.getCustomImplementationRef();
    }

    return beanName;
}

From source file:org.springframework.data.repository.config.RepositoryBeanDefinitionParser.java

/**
 * Registers a generic repository factory bean for a bean with the given name and the provided configuration context.
 * //from   w w w  .  ja  v a 2  s. c  om
 * @param parser
 * @param name
 * @param context
 */
private void registerGenericRepositoryFactoryBean(
        RepositoryConfiguration<XmlRepositoryConfigurationSource> configuration, ParserContext parser) {

    RepositoryBeanDefinitionBuilder definitionBuilder = new RepositoryBeanDefinitionBuilder(configuration,
            extension);

    try {

        BeanDefinitionBuilder builder = definitionBuilder.build(parser.getRegistry(),
                parser.getReaderContext().getResourceLoader());

        extension.postProcess(builder, configuration.getConfigurationSource());

        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
        beanDefinition.setSource(configuration.getSource());

        if (LOG.isDebugEnabled()) {
            LOG.debug("Registering repository: " + configuration.getBeanId() + " - Interface: "
                    + configuration.getRepositoryInterface() + " - Factory: "
                    + extension.getRepositoryFactoryClassName());
        }

        BeanComponentDefinition definition = new BeanComponentDefinition(beanDefinition,
                configuration.getBeanId());
        parser.registerBeanComponent(definition);
    } catch (RuntimeException e) {
        handleError(e, configuration.getConfigurationSource().getElement(), parser.getReaderContext());
    }
}

From source file:org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig.java

public void registerBean(ReaderEventListener eventListener, ClassLoader classloader) throws IOException {
    IJavaProject project = this.configClass.getJavaProject();
    if (project == null) {
        return;/* w w w . ja  v  a  2 s  . c o  m*/
    }

    CachingJdtMetadataReaderFactory metadataReaderFactory = new CachingJdtMetadataReaderFactory(project,
            classloader);
    MetadataReader metadataReader = metadataReaderFactory
            .getMetadataReader(this.configClass.getFullyQualifiedName());

    AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(
            metadataReader.getAnnotationMetadata());

    //      AnnotationMetadata metadata = abd.getMetadata();
    //      if (metadata.isAnnotated(Profile.class.getName())) {
    //         AnnotationAttributes profile = MetadataUtils.attributesFor(metadata, Profile.class);
    //         if (!this.environment.acceptsProfiles(profile.getStringArray("value"))) {
    //            return;
    //         }
    //      }
    //      ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
    //      abd.setScope(scopeMetadata.getScopeName());
    abd.setScope(BeanDefinition.SCOPE_SINGLETON);

    AnnotationBeanNameGenerator nameGenerator = new AnnotationBeanNameGenerator();
    String beanName = nameGenerator.generateBeanName(abd, this.registry);
    //      AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
    //      if (qualifiers != null) {
    //         for (Class<? extends Annotation> qualifier : qualifiers) {
    //            if (Primary.class.equals(qualifier)) {
    //               abd.setPrimary(true);
    //            }
    //            else if (Lazy.class.equals(qualifier)) {
    //               abd.setLazyInit(true);
    //            }
    //            else {
    //               abd.addQualifier(new AutowireCandidateQualifier(qualifier));
    //            }
    //         }
    //      }
    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
    //      definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
    BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
    eventListener.componentRegistered(new BeanComponentDefinition(abd, beanName));
}

From source file:org.springframework.integration.config.DefaultConfiguringBeanFactoryPostProcessor.java

/**
 * Register an error channel in the given BeanDefinitionRegistry.
 *///from   w w w  .  ja  v a  2 s . c o  m
private void registerErrorChannel(BeanDefinitionRegistry registry) {
    if (this.logger.isInfoEnabled()) {
        this.logger.info("No bean named '" + IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME
                + "' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.");
    }
    registry.registerBeanDefinition(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME,
            new RootBeanDefinition(PublishSubscribeChannel.class));

    BeanDefinition loggingHandler = BeanDefinitionBuilder.genericBeanDefinition(LoggingHandler.class)
            .addConstructorArgValue("ERROR").getBeanDefinition();

    String errorLoggerBeanName = ERROR_LOGGER_BEAN_NAME + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX;
    registry.registerBeanDefinition(errorLoggerBeanName, loggingHandler);

    BeanDefinitionBuilder loggingEndpointBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(ConsumerEndpointFactoryBean.class)
            .addPropertyReference("handler", errorLoggerBeanName)
            .addPropertyValue("inputChannelName", IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);

    BeanComponentDefinition componentDefinition = new BeanComponentDefinition(
            loggingEndpointBuilder.getBeanDefinition(), ERROR_LOGGER_BEAN_NAME);
    BeanDefinitionReaderUtils.registerBeanDefinition(componentDefinition, registry);
}

From source file:org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor.java

/**
 * Register an error channel in the given BeanDefinitionRegistry.
 */// w w  w . j  a  va  2  s .  c  om
private void registerErrorChannel(BeanDefinitionRegistry registry) {
    if (logger.isInfoEnabled()) {
        logger.info("No bean named '" + IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME
                + "' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.");
    }
    RootBeanDefinition errorChannelDef = new RootBeanDefinition();
    errorChannelDef
            .setBeanClassName(IntegrationNamespaceUtils.BASE_PACKAGE + ".channel.PublishSubscribeChannel");
    BeanDefinitionHolder errorChannelHolder = new BeanDefinitionHolder(errorChannelDef,
            IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);
    BeanDefinitionReaderUtils.registerBeanDefinition(errorChannelHolder, registry);
    BeanDefinitionBuilder loggingHandlerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(IntegrationNamespaceUtils.BASE_PACKAGE + ".handler.LoggingHandler");
    loggingHandlerBuilder.addConstructorArgValue("ERROR");
    BeanDefinitionBuilder loggingEndpointBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(IntegrationNamespaceUtils.BASE_PACKAGE + ".endpoint.EventDrivenConsumer");
    loggingEndpointBuilder.addConstructorArgReference(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);
    loggingEndpointBuilder.addConstructorArgValue(loggingHandlerBuilder.getBeanDefinition());
    BeanComponentDefinition componentDefinition = new BeanComponentDefinition(
            loggingEndpointBuilder.getBeanDefinition(), ERROR_LOGGER_BEAN_NAME);
    BeanDefinitionReaderUtils.registerBeanDefinition(componentDefinition, registry);
}

From source file:org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor.java

/**
 * Register a TaskScheduler in the given BeanDefinitionRegistry.
 *//*  w  w  w . ja  v  a2  s .  c o  m*/
private void registerTaskScheduler(BeanDefinitionRegistry registry) {
    if (logger.isInfoEnabled()) {
        logger.info("No bean named '" + IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME
                + "' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.");
    }
    BeanDefinitionBuilder schedulerBuilder = BeanDefinitionBuilder
            .genericBeanDefinition("org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler");
    schedulerBuilder.addPropertyValue("poolSize", 10);
    schedulerBuilder.addPropertyValue("threadNamePrefix", "task-scheduler-");
    schedulerBuilder.addPropertyValue("rejectedExecutionHandler", new CallerRunsPolicy());
    BeanDefinitionBuilder errorHandlerBuilder = BeanDefinitionBuilder.genericBeanDefinition(
            IntegrationNamespaceUtils.BASE_PACKAGE + ".channel.MessagePublishingErrorHandler");
    errorHandlerBuilder.addPropertyReference("defaultErrorChannel",
            IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);
    schedulerBuilder.addPropertyValue("errorHandler", errorHandlerBuilder.getBeanDefinition());
    BeanComponentDefinition schedulerComponent = new BeanComponentDefinition(
            schedulerBuilder.getBeanDefinition(), IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME);
    BeanDefinitionReaderUtils.registerBeanDefinition(schedulerComponent, registry);
}

From source file:org.springframework.ldap.config.ContextSourceParser.java

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(LdapContextSource.class);

    String username = element.getAttribute(ATT_USERNAME);
    String password = element.getAttribute(ATT_PASSWORD);
    String url = element.getAttribute(ATT_URL);
    Assert.hasText(url, "url attribute must be specified");

    builder.addPropertyValue("userDn", username);
    builder.addPropertyValue("password", password);

    BeanDefinitionBuilder urlsBuilder = BeanDefinitionBuilder.rootBeanDefinition(UrlsFactory.class)
            .setFactoryMethod("urls").addConstructorArgValue(url);

    builder.addPropertyValue("urls", urlsBuilder.getBeanDefinition());
    builder.addPropertyValue("base", getString(element, ATT_BASE, ""));
    builder.addPropertyValue("referral", getString(element, ATT_REFERRAL, null));

    boolean anonymousReadOnly = getBoolean(element, ATT_ANONYMOUS_READ_ONLY, false);
    builder.addPropertyValue("anonymousReadOnly", anonymousReadOnly);
    boolean nativePooling = getBoolean(element, ATT_NATIVE_POOLING, false);
    builder.addPropertyValue("pooled", nativePooling);

    String authStrategyRef = element.getAttribute(ATT_AUTHENTICATION_STRATEGY_REF);
    if (StringUtils.hasText(authStrategyRef)) {
        builder.addPropertyReference("authenticationStrategy", authStrategyRef);
    }/* w ww  .j  av  a  2 s .  c o m*/

    String authSourceRef = element.getAttribute(ATT_AUTHENTICATION_SOURCE_REF);
    if (StringUtils.hasText(authSourceRef)) {
        builder.addPropertyReference("authenticationSource", authSourceRef);
    } else {
        Assert.hasText(username,
                "username attribute must be specified unless an authentication-source-ref explicitly configured");
        Assert.hasText(password,
                "password attribute must be specified unless an authentication-source-ref explicitly configured");
    }

    String baseEnvPropsRef = element.getAttribute(ATT_BASE_ENV_PROPS_REF);
    if (StringUtils.hasText(baseEnvPropsRef)) {
        builder.addPropertyReference("baseEnvironmentProperties", baseEnvPropsRef);
    }

    BeanDefinition targetContextSourceDefinition = builder.getBeanDefinition();
    targetContextSourceDefinition = applyPoolingIfApplicable(targetContextSourceDefinition, element,
            nativePooling);

    BeanDefinition actualContextSourceDefinition = targetContextSourceDefinition;
    if (!anonymousReadOnly) {
        BeanDefinitionBuilder proxyBuilder = BeanDefinitionBuilder
                .rootBeanDefinition(TransactionAwareContextSourceProxy.class);
        proxyBuilder.addConstructorArgValue(targetContextSourceDefinition);
        actualContextSourceDefinition = proxyBuilder.getBeanDefinition();
    }

    String id = getString(element, AbstractBeanDefinitionParser.ID_ATTRIBUTE, DEFAULT_ID);
    parserContext.registerBeanComponent(new BeanComponentDefinition(actualContextSourceDefinition, id));

    return actualContextSourceDefinition;
}