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

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

Introduction

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

Prototype

public String getBeanName() 

Source Link

Document

Return the primary name of the bean, as specified for the bean definition.

Usage

From source file:org.xeustechnologies.jcl.spring.JclBeanDefinitionDecorator.java

public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder holder, ParserContext parserContext) {
    String jclRef = node.getAttributes().getNamedItem(JCL_REF).getNodeValue();

    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setFactoryBeanName(JCL_FACTORY);/* w w  w  .j  a  v  a2  s . c o  m*/
    bd.setFactoryMethodName(JCL_FACTORY_METHOD);
    bd.setConstructorArgumentValues(holder.getBeanDefinition().getConstructorArgumentValues());
    bd.setPropertyValues(holder.getBeanDefinition().getPropertyValues());
    bd.getConstructorArgumentValues().addIndexedArgumentValue(0,
            new ConstructorArgumentValues.ValueHolder(parserContext.getRegistry().getBeanDefinition(jclRef)));
    bd.getConstructorArgumentValues().addIndexedArgumentValue(1,
            new ConstructorArgumentValues.ValueHolder(holder.getBeanDefinition().getBeanClassName()));

    BeanDefinitionHolder newHolder = new BeanDefinitionHolder(bd, holder.getBeanName());

    createDependencyOnJcl(node, newHolder, parserContext);

    return newHolder;
}

From source file:org.kuali.rice.krad.datadictionary.MessageBeanProcessor.java

/**
 * Retrieves the test associated with the message give by the message key string
 *
 * @param messageKeyStr key string for the message, can contain just the key, or also the component and/or
 * namespace. If component or namespace not given it is determined from the bean stack
 * @param nestedBeanStack bean stack that contains the property for which the message applies
 * @return String test associated with the message
 *///  w  w w.j a  va  2  s . co  m
protected String getMessageTextForKey(String messageKeyStr, Stack<BeanDefinitionHolder> nestedBeanStack) {
    String namespace = null;
    String componentCode = null;
    String key = null;

    // check for specification of namespace and component
    if (StringUtils.contains(messageKeyStr, ":")) {
        String[] messageParams = StringUtils.split(messageKeyStr, ":");

        if (messageParams.length == 3) {
            namespace = messageParams[0];
            componentCode = messageParams[1];
            key = messageParams[2];
        } else if (messageParams.length == 2) {
            componentCode = messageParams[0];
            key = messageParams[1];
        } else {
            throw new RiceRuntimeException("Message key '" + messageKeyStr + "' has an invalid format");
        }
    } else {
        key = messageKeyStr;
    }

    if (StringUtils.isBlank(namespace)) {
        namespace = getNamespaceForBeanInStack(nestedBeanStack);
    }

    if (StringUtils.isBlank(componentCode)) {
        for (int i = nestedBeanStack.size() - 1; i >= 0; i--) {
            BeanDefinitionHolder definitionHolder = nestedBeanStack.get(i);
            componentCode = getComponentForBean(definitionHolder.getBeanName(),
                    definitionHolder.getBeanDefinition());
            if (StringUtils.isNotBlank(componentCode)) {
                break;
            }
        }
    }

    String messageText = null;
    if (StringUtils.isNotBlank(namespace) && StringUtils.isNotBlank(componentCode)
            && StringUtils.isNotBlank(key)) {
        messageText = getMessageService().getMessageText(namespace, componentCode, key);
    }

    return messageText;
}

From source file:org.kuali.rice.krad.datadictionary.MessageBeanProcessor.java

/**
 * Walks up the stack of bean definitions until a namespace is found and returns that namespace
 *
 * @param nestedBeanStack stack of bean definitions to find namespace for
 * @return String namespace found in stack or null if one was not found
 *///  www  .  j  a  v a2s .c o  m
protected String getNamespaceForBeanInStack(Stack<BeanDefinitionHolder> nestedBeanStack) {
    String namespace = null;

    if (nestedBeanStack != null) {
        for (int i = nestedBeanStack.size() - 1; i >= 0; i--) {
            BeanDefinitionHolder definitionHolder = nestedBeanStack.get(i);
            namespace = getNamespaceForBean(definitionHolder.getBeanName(),
                    definitionHolder.getBeanDefinition());
            if (StringUtils.isNotBlank(namespace)) {
                break;
            }
        }
    }

    return namespace;
}

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

@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder beanDefinitionHolder,
        ParserContext parserContext) {//from 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.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.
 *//*  ww  w  .ja  va 2  s  .c o  m*/
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.beans.factory.xml.DefaultBeanDefinitionDocumentReader.java

/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 *//* w w  w  .j a  v  a 2 s .  co m*/
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // Register the final decorated instance.
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
        } catch (BeanDefinitionStoreException ex) {
            getReaderContext().error(
                    "Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex);
        }
        // Send registration event.
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}

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

/**
 * Register the {@link Configuration} class itself as a bean definition.
 *//*from  w  w  w .java 2 s  .  c om*/
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.ConfigurationClassParser.java

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

    for (BeanDefinitionHolder holder : configCandidates) {
        BeanDefinition bd = holder.getBeanDefinition();
        try {//from w  ww  .  j a  v a  2  s  . c o m
            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  w ww . j  av  a 2  s  . 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 {// w w  w .  j  a  v  a  2  s  . co 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;
}