Example usage for org.springframework.beans.factory.config BeanDefinitionHolder getBeanDefinition

List of usage examples for org.springframework.beans.factory.config BeanDefinitionHolder getBeanDefinition

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config BeanDefinitionHolder getBeanDefinition.

Prototype

public BeanDefinition getBeanDefinition() 

Source Link

Document

Return the wrapped BeanDefinition.

Usage

From source file:org.kuali.rice.krad.datadictionary.parse.CustomSchemaParser.java

/**
 * Parses a bean of the spring namespace.
 *
 * @param tag - The Element to be parsed.
 * @return The parsed bean./*  w w  w  . ja  v  a  2 s .  c o m*/
 */
protected Object parseSpringBean(Element tag, ParserContext parserContext) {
    if (tag.getLocalName().compareTo("ref") == 0) {
        // Create the referenced bean by creating a new bean and setting its parent to the referenced bean
        // then replace grand child with it
        Element temp = tag.getOwnerDocument().createElement("bean");
        temp.setAttribute("parent", tag.getAttribute("bean"));
        tag = temp;
        return new RuntimeBeanReference(tag.getAttribute("parent"));
    }

    //peel off p: properties an make them actual property nodes - p-namespace does not work properly (unknown cause)
    Document document = tag.getOwnerDocument();
    NamedNodeMap attributes = tag.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        String name = attribute.getNodeName();
        if (name.startsWith("p:")) {
            Element property = document.createElement("property");
            property.setAttribute("name", StringUtils.removeStart(name, "p:"));
            property.setAttribute("value", attribute.getTextContent());

            if (tag.getFirstChild() != null) {
                tag.insertBefore(property, tag.getFirstChild());
            } else {
                tag.appendChild(property);
            }
        }
    }

    // Create the bean definition for the grandchild and return it.
    BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
    BeanDefinitionHolder bean = delegate.parseBeanDefinitionElement(tag);

    // Creates a custom name for the new bean.
    String name = bean.getBeanDefinition().getParentName() + "$Customchild" + beanNumber;
    if (tag.getAttribute("id") != null && !StringUtils.isEmpty(tag.getAttribute("id"))) {
        name = tag.getAttribute("id");
    } else {
        beanNumber++;
    }

    return new BeanDefinitionHolder(bean.getBeanDefinition(), name);
}

From source file:org.mule.config.spring.MuleHierarchicalBeanDefinitionParserDelegate.java

protected BeanDefinition handleSpringElements(Element element, BeanDefinition parent) {

    // these are only called if they are at a "top level" - if they are nested inside
    // other spring elements then spring will handle them itself

    if (SpringXMLUtils.isLocalName(element, BEANS)) {
        // the delegate doesn't support the full spring schema, but it seems that
        // we can invoke the DefaultBeanDefinitionDocumentReader via registerBeanDefinitions
        // but we need to create a new DOM document from the element first
        try {/* w w  w .ja va  2 s  .co  m*/
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            doc.appendChild(doc.importNode(element, true));
            spring.registerBeanDefinitions(doc, getReaderContext());
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        return parent;
    }

    else if (SpringXMLUtils.isLocalName(element, PROPERTY_ELEMENT)) {
        parsePropertyElement(element, parent);
        return parent;
    }

    // i am trying to keep these to a minimum - using anything but "bean" is a recipe
    // for disaster - we already have problems with "property", for example.

    //        else if (isLocalName(element, MAP_ELEMENT))
    //        {
    //            // currently unused?
    //            parseMapElement(element, bd);
    //        }
    //        else if (isLocalName(element, LIST_ELEMENT))
    //        {
    //            // currently unused?
    //            parseListElement(element, bd);
    //        }
    //        else if (isLocalName(element, SET_ELEMENT))
    //        {
    //            // currently unused?
    //            parseSetElement(element, bd);
    //        }

    else if (SpringXMLUtils.isLocalName(element, BEAN_ELEMENT)) {
        BeanDefinitionHolder holder = parseBeanDefinitionElement(element, parent);
        registerBeanDefinitionHolder(holder);
        return holder.getBeanDefinition();
    } else {
        throw new IllegalStateException(
                "Unexpected Spring element: " + SpringXMLUtils.elementToString(element));
    }
}

From source file:org.pentaho.platform.engine.core.system.objfac.spring.BeanPublishParser.java

@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder beanDefinitionHolder,
        ParserContext parserContext) {/*w w  w  . ja v a 2 s  .  com*/

    String publishType = null;
    String beanClassName;

    // If this is a republish of a pen:bean, the class will be a FactoryBean and the actual class returned back the
    // factory will be stored as an attribute.
    if (beanDefinitionHolder.getBeanDefinition().getAttribute("originalClassName") != null) {
        beanClassName = beanDefinitionHolder.getBeanDefinition().getAttribute("originalClassName").toString();
    } else {
        beanClassName = beanDefinitionHolder.getBeanDefinition().getBeanClassName();
    }

    if (node.getAttributes().getNamedItem(ATTR) != null) { // publish as type if specified
        publishType = node.getAttributes().getNamedItem(ATTR).getNodeValue();
    } else { // fallback to publish as itself
        publishType = beanClassName;
    }

    // capture the "ID" of the bean as an attribute so it can be queried for
    beanDefinitionHolder.getBeanDefinition().setAttribute("id", beanDefinitionHolder.getBeanName());
    NodeList nodes = node.getChildNodes();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        if (stripNamespace(n.getNodeName()).equals(Const.ATTRIBUTES)) {
            NodeList attrnodes = n.getChildNodes();

            for (int y = 0; y < attrnodes.getLength(); y++) {
                Node an = attrnodes.item(y);
                if (stripNamespace(an.getNodeName()).equals(Const.ATTR)) {
                    beanDefinitionHolder.getBeanDefinition().setAttribute(
                            an.getAttributes().getNamedItem(Const.KEY).getNodeValue(),
                            an.getAttributes().getNamedItem(Const.VALUE).getNodeValue());
                }
            }
        }
    }

    try {
        List<Class<?>> classesToPublish = new ArrayList<Class<?>>();

        Class<?> clazz = findClass(beanClassName);

        if (specialPublishTypes.INTERFACES.name().equals(publishType)) {
            if (clazz.isInterface()) { // publish as self if interface already (re-publish flow)
                classesToPublish.add(clazz);
            } else {
                classesToPublish.addAll(ClassUtils.getAllInterfaces(clazz));
            }
        } else if (specialPublishTypes.CLASSES.name().equals(publishType)) {

            classesToPublish.addAll(ClassUtils.getAllSuperclasses(clazz));
            classesToPublish.add(clazz);
        } else if (specialPublishTypes.ALL.name().equals(publishType)) {

            classesToPublish.addAll(ClassUtils.getAllInterfaces(clazz));
            classesToPublish.addAll(ClassUtils.getAllSuperclasses(clazz));
            classesToPublish.add(clazz);
        } else {
            classesToPublish.add(getClass().getClassLoader().loadClass(publishType));
        }

        String beanFactoryId = null;

        if (parserContext.getRegistry().containsBeanDefinition(Const.FACTORY_MARKER) == false) {
            beanFactoryId = UUID.randomUUID().toString();
            parserContext.getRegistry().registerBeanDefinition(Const.FACTORY_MARKER,
                    BeanDefinitionBuilder.genericBeanDefinition(Marker.class)
                            .setScope(BeanDefinition.SCOPE_PROTOTYPE).addConstructorArgValue(beanFactoryId)
                            .getBeanDefinition());
        } else {
            beanFactoryId = (String) parserContext.getRegistry().getBeanDefinition(Const.FACTORY_MARKER)
                    .getConstructorArgumentValues().getArgumentValue(0, String.class).getValue();
        }

        for (Class cls : classesToPublish) {
            PublishedBeanRegistry.registerBean(beanDefinitionHolder.getBeanName(), cls, beanFactoryId);
        }

    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Cannot find class for publish type: " + publishType
                + " specified on publish of bean id: " + beanDefinitionHolder.getBeanName(), e);
    }
    return beanDefinitionHolder;
}

From source file:org.springframework.amqp.rabbit.stocks.context.RefreshScope.java

private static BeanDefinitionHolder createScopedProxy(String beanName, BeanDefinition definition,
        BeanDefinitionRegistry registry, boolean proxyTargetClass) {
    BeanDefinitionHolder proxyHolder = ScopedProxyUtils
            .createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, proxyTargetClass);
    registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
    return proxyHolder;
}

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

/**
 * Given a PropertyValue, return a value, resolving any references to other
 * beans in the factory if necessary. The value could be:
 * <li>A BeanDefinition, which leads to the creation of a corresponding
 * new bean instance. Singleton flags and names of such "inner beans"
 * are always ignored: Inner beans are anonymous prototypes.
 * <li>A RuntimeBeanReference, which must be resolved.
 * <li>A ManagedList. This is a special collection that may contain
 * RuntimeBeanReferences or Collections that will need to be resolved.
 * <li>A ManagedSet. May also contain RuntimeBeanReferences or
 * Collections that will need to be resolved.
 * <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
 * or Collection that will need to be resolved.
 * <li>An ordinary object or <code>null</code>, in which case it's left alone.
 *//*from w  ww. java 2  s  .  c  om*/
public Object resolveValueIfNecessary(String argName, Object value) throws BeansException {
    // We must check each value to see whether it requires a runtime reference
    // to another bean to be resolved.
    if (value instanceof BeanDefinitionHolder) {
        // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
        BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
        return resolveInnerBeanDefinition(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
    } else if (value instanceof BeanDefinition) {
        // Resolve plain BeanDefinition, without contained name: use dummy name.
        BeanDefinition bd = (BeanDefinition) value;
        return resolveInnerBeanDefinition(argName, "(inner bean)", bd);
    } else if (value instanceof RuntimeBeanReference) {
        RuntimeBeanReference ref = (RuntimeBeanReference) value;
        return resolveReference(argName, ref);
    } else if (value instanceof ManagedList) {
        // May need to resolve contained runtime references.
        return resolveManagedList(argName, (List) value);
    } else if (value instanceof ManagedSet) {
        // May need to resolve contained runtime references.
        return resolveManagedSet(argName, (Set) value);
    } else if (value instanceof ManagedMap) {
        // May need to resolve contained runtime references.
        return resolveManagedMap(argName, (Map) value);
    } else if (value instanceof TypedStringValue) {
        // Convert value to target type here.
        TypedStringValue typedStringValue = (TypedStringValue) value;
        try {
            return this.beanFactory.doTypeConversionIfNecessary(typedStringValue.getValue(),
                    typedStringValue.getTargetType());
        } catch (Throwable ex) {
            // Improve the message by showing the context.
            throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,
                    "Error converting typed String value for " + argName, ex);
        }
    } else {
        // No need to resolve value...
        return value;
    }
}

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

/**
 * Register the {@link Configuration} class itself as a bean definition.
 *///from w w w  .ja v  a 2  s.  c  o  m
private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) {
    AnnotationMetadata metadata = configClass.getMetadata();
    AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata);

    ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef);
    configBeanDef.setScope(scopeMetadata.getScopeName());
    String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry);
    AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata);

    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName);
    definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder,
            this.registry);
    this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition());
    configClass.setBeanName(configBeanName);

    if (logger.isDebugEnabled()) {
        logger.debug("Registered bean definition for imported class '" + configBeanName + "'");
    }
}

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

/**
 * Read the given {@link BeanMethod}, registering bean definitions
 * with the BeanDefinitionRegistry based on its contents.
 *///from   ww w  .  ja  v  a 2  s  .c  om
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
    ConfigurationClass configClass = beanMethod.getConfigurationClass();
    MethodMetadata metadata = beanMethod.getMetadata();
    String methodName = metadata.getMethodName();

    // Do we need to mark the bean as skipped by its condition?
    if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
        configClass.skippedBeanMethods.add(methodName);
        return;
    }
    if (configClass.skippedBeanMethods.contains(methodName)) {
        return;
    }

    AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
    Assert.state(bean != null, "No @Bean annotation attributes");

    // Consider name and any aliases
    List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
    String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

    // Register aliases even when overridden
    for (String alias : names) {
        this.registry.registerAlias(beanName, alias);
    }

    // Has this effectively been overridden before (e.g. via XML)?
    if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
        if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
            throw new BeanDefinitionStoreException(
                    beanMethod.getConfigurationClass().getResource().getDescription(), beanName,
                    "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName()
                            + "' clashes with bean name for containing configuration class; please make those names unique!");
        }
        return;
    }

    ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
    beanDef.setResource(configClass.getResource());
    beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

    if (metadata.isStatic()) {
        // static @Bean method
        beanDef.setBeanClassName(configClass.getMetadata().getClassName());
        beanDef.setFactoryMethodName(methodName);
    } else {
        // instance @Bean method
        beanDef.setFactoryBeanName(configClass.getBeanName());
        beanDef.setUniqueFactoryMethodName(methodName);
    }
    beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

    AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

    Autowire autowire = bean.getEnum("autowire");
    if (autowire.isAutowire()) {
        beanDef.setAutowireMode(autowire.value());
    }

    String initMethodName = bean.getString("initMethod");
    if (StringUtils.hasText(initMethodName)) {
        beanDef.setInitMethodName(initMethodName);
    }

    String destroyMethodName = bean.getString("destroyMethod");
    beanDef.setDestroyMethodName(destroyMethodName);

    // Consider scoping
    ScopedProxyMode proxyMode = ScopedProxyMode.NO;
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
    if (attributes != null) {
        beanDef.setScope(attributes.getString("value"));
        proxyMode = attributes.getEnum("proxyMode");
        if (proxyMode == ScopedProxyMode.DEFAULT) {
            proxyMode = ScopedProxyMode.NO;
        }
    }

    // Replace the original bean definition with the target one, if necessary
    BeanDefinition beanDefToRegister = beanDef;
    if (proxyMode != ScopedProxyMode.NO) {
        BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
                new BeanDefinitionHolder(beanDef, beanName), this.registry,
                proxyMode == ScopedProxyMode.TARGET_CLASS);
        beanDefToRegister = new ConfigurationClassBeanDefinition(
                (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata);
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Registering bean definition for @Bean method %s.%s()",
                configClass.getMetadata().getClassName(), beanName));
    }

    this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}

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

public void parse(Set<BeanDefinitionHolder> configCandidates) {
    this.deferredImportSelectors = new LinkedList<>();

    for (BeanDefinitionHolder holder : configCandidates) {
        BeanDefinition bd = holder.getBeanDefinition();
        try {//from   w w  w  . j  a va2  s .c om
            if (bd instanceof AnnotatedBeanDefinition) {
                parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
            } else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
                parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
            } else {
                parse(bd.getBeanClassName(), holder.getBeanName());
            }
        } catch (BeanDefinitionStoreException ex) {
            throw ex;
        } catch (Throwable ex) {
            throw new BeanDefinitionStoreException(
                    "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
        }
    }

    processDeferredImportSelectors();
}

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

/**
 * Apply processing and build a complete {@link ConfigurationClass} by reading the
 * annotations, members and methods from the source class. This method can be called
 * multiple times as relevant sources are discovered.
 * @param configClass the configuration class being build
 * @param sourceClass a source class//from   www. j  a v  a 2s. c o m
 * @return the superclass, or {@code null} if none found or previously processed
 */
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
        throws IOException {

    // Recursively process any member (nested) classes first
    processMemberClasses(configClass, sourceClass);

    // Process any @PropertySource annotations
    for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
            sourceClass.getMetadata(), PropertySources.class,
            org.springframework.context.annotation.PropertySource.class)) {
        if (this.environment instanceof ConfigurableEnvironment) {
            processPropertySource(propertySource);
        } else {
            logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName()
                    + "]. Reason: Environment must implement ConfigurableEnvironment");
        }
    }

    // Process any @ComponentScan annotations
    Set<AnnotationAttributes> componentScans = AnnotationConfigUtils
            .attributesForRepeatable(sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
    if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(),
            ConfigurationPhase.REGISTER_BEAN)) {
        for (AnnotationAttributes componentScan : componentScans) {
            // The config class is annotated with @ComponentScan -> perform the scan immediately
            Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan,
                    sourceClass.getMetadata().getClassName());
            // Check the set of scanned definitions for any further config classes and parse recursively if needed
            for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
                if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(),
                        this.metadataReaderFactory)) {
                    parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
                }
            }
        }
    }

    // Process any @Import annotations
    processImports(configClass, sourceClass, getImports(sourceClass), true);

    // Process any @ImportResource annotations
    AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(),
            ImportResource.class);
    if (importResource != null) {
        String[] resources = importResource.getStringArray("locations");
        Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
        for (String resource : resources) {
            String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
            configClass.addImportedResource(resolvedResource, readerClass);
        }
    }

    // Process individual @Bean methods
    Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
    for (MethodMetadata methodMetadata : beanMethods) {
        configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
    }

    // Process default methods on interfaces
    processInterfaces(configClass, sourceClass);

    // Process superclass, if any
    if (sourceClass.getMetadata().hasSuperClass()) {
        String superclass = sourceClass.getMetadata().getSuperClassName();
        if (superclass != null && !superclass.startsWith("java")
                && !this.knownSuperclasses.containsKey(superclass)) {
            this.knownSuperclasses.put(superclass, configClass);
            // Superclass found, return its annotation metadata and recurse
            return sourceClass.getSuperClass();
        }
    }

    // No superclass -> processing is complete
    return null;
}

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

private BeanMetadataElement parseChild(String chainHandlerId, Element element, int order,
        ParserContext parserContext, BeanDefinition parentDefinition) {

    BeanDefinitionHolder holder = null;

    String id = element.getAttribute(ID_ATTRIBUTE);
    boolean hasId = StringUtils.hasText(id);
    String handlerComponentName = chainHandlerId + "$child" + (hasId ? "." + id : "#" + order);

    if ("bean".equals(element.getLocalName())) {
        holder = parserContext.getDelegate().parseBeanDefinitionElement(element, parentDefinition);
    } else {// ww  w  .  ja v  a 2s .  c o m

        this.validateChild(element, parserContext);

        BeanDefinition beanDefinition = parserContext.getDelegate().parseCustomElement(element,
                parentDefinition);
        if (beanDefinition == null) {
            parserContext.getReaderContext().error("child BeanDefinition must not be null", element);
            return null;
        } else {
            holder = new BeanDefinitionHolder(beanDefinition,
                    handlerComponentName + IntegrationNamespaceUtils.HANDLER_ALIAS_SUFFIX);
        }
    }

    holder.getBeanDefinition().getPropertyValues().add("componentName", handlerComponentName);

    if (hasId) {
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, parserContext.getRegistry());
        return new RuntimeBeanReference(holder.getBeanName());
    }

    return holder;
}