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:com.mtgi.analytics.aop.config.v11.BtManagerBeanDefinitionParser.java

/** 
 * called by nested tags to push inner beans into the enclosing {@link BehaviorTrackingManagerImpl}.
 * @return <span>true if the inner bean was added to an enclosing {@link BehaviorTrackingManagerImpl}.  Otherwise, the bean definition
 * is not nested inside a &lt;bt:manager&gt; tag and therefore will have to be registered as a global bean in the application
 * context.</span>// w  w  w.  ja  v a2 s.c o m
 */
protected static boolean registerNestedBean(BeanDefinitionHolder nested, String parentProperty,
        ParserContext parserContext) {
    //add parsed inner bean element to containing manager definition; e.g. persister or SessionContext impls.
    CompositeComponentDefinition parent = parserContext.getContainingComponent();
    if (parent instanceof ManagerComponentDefinition) {
        //we are nested; add to enclosing bean def.
        ManagerComponentDefinition mcd = (ManagerComponentDefinition) parent;
        BeanDefinition managerDef = parserContext.getContainingBeanDefinition();

        MutablePropertyValues props = managerDef.getPropertyValues();
        PropertyValue current = props.getPropertyValue(parentProperty);
        boolean innerBean = true;

        if (current != null) {
            //if the original value is a reference, replace it with an alias to the nested bean definition.
            //this means the nested bean takes the place of the default definition
            //in other places where it might be referenced, as well as during mbean export
            Object value = current.getValue();
            DefaultListableBeanFactory factory = mcd.getTemplateFactory();
            if (value instanceof RuntimeBeanReference) {
                String ref = ((RuntimeBeanReference) value).getBeanName();

                if (factory.getBeanDefinition(ref) == nested.getBeanDefinition()) {
                    //the nested definition is the same as the default definition
                    //by reference, so we don't need to make it an inner bean definition.
                    innerBean = false;
                }
            }
        }
        if (innerBean)
            props.addPropertyValue(parentProperty, nested);
        mcd.addNestedProperty(parentProperty);
        return true;
    }
    //bean is not nested inside bt:manager
    return false;
}

From source file:org.jdal.aop.config.SerializableProxyBeanDefinitionDecorator.java

public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
    boolean proxyTargetClass = true;
    if (node instanceof Element) {
        Element ele = (Element) node;
        if (ele.hasAttribute(PROXY_TARGET_CLASS)) {
            proxyTargetClass = Boolean.valueOf(ele.getAttribute(PROXY_TARGET_CLASS));
        }/*from w  ww  .j a  v a 2  s  .  c o m*/
    }

    // Register the original bean definition
    BeanDefinitionHolder holder = SerializableProxyUtils.createSerializableProxy(definition,
            parserContext.getRegistry(), proxyTargetClass);
    String targetBeanName = SerializableProxyUtils.getTargetBeanName(definition.getBeanName());
    parserContext.getReaderContext().fireComponentRegistered(
            new BeanComponentDefinition(definition.getBeanDefinition(), targetBeanName));
    return holder;
}

From source file:org.smf4j.spring.RegistryNodeTemplateDefinitionParser.java

protected String parseCustom(ParserContext context, Element element, BeanDefinition containingBean) {
    String name = getName(context, element);
    String ref = element.getAttribute(REF_ATTR);

    String customBeanId = null;//from ww w.j  a  v  a  2  s  .c om
    if (StringUtils.hasLength(ref)) {
        customBeanId = ref;
    } else {
        // Grab the single child element, that should define or point
        // to the custom Accumulator or Calcuation bean definition.
        NodeList childList = element.getChildNodes();
        Element child = null;
        for (int i = 0; i < childList.getLength(); i++) {
            Node childNode = childList.item(i);
            if (!(childNode instanceof Element)) {
                continue;
            }

            if (child != null) {
                context.getReaderContext()
                        .error("'custom' elements without a 'ref' attribute must "
                                + "have exactly one 'bean', 'ref', or 'idref' child" + " element.",
                                context.extractSource(element));
            }
            child = (Element) childNode;
        }

        if (child == null) {
            context.getReaderContext()
                    .error("'custom' elements must specify a 'ref' attribute or a "
                            + "single 'bean', 'ref', or 'idref' child element.",
                            context.extractSource(element));
        }

        // Parse the contents of the custom bean
        Object o = context.getDelegate().parsePropertySubElement(child, containingBean);

        if (o instanceof BeanDefinitionHolder) {
            BeanDefinitionHolder bdh = (BeanDefinitionHolder) o;
            customBeanId = bdh.getBeanName();
            if (!StringUtils.hasLength(customBeanId)) {
                // They didn't give their bean an id, so we'll need to
                // generate one for it now.
                customBeanId = context.getReaderContext().generateBeanName(bdh.getBeanDefinition());
            }

            // Register this bean
            context.getRegistry().registerBeanDefinition(customBeanId, bdh.getBeanDefinition());
        } else if (o instanceof RuntimeBeanReference) {
            RuntimeBeanReference rbr = (RuntimeBeanReference) o;
            customBeanId = rbr.getBeanName();
        } else if (o instanceof RuntimeBeanNameReference) {
            RuntimeBeanNameReference rbnr = (RuntimeBeanNameReference) o;
            customBeanId = rbnr.getBeanName();
        }
    }

    // Create proxy that associates the given name with this child
    BeanDefinitionBuilder accProxyBdb = getBdb(RegistryNodeChildProxy.class);
    accProxyBdb.addPropertyValue(NAME_ATTR, name);
    accProxyBdb.addPropertyValue(CHILD_ATTR, customBeanId);
    accProxyBdb.getRawBeanDefinition().setSource(element);

    return context.getReaderContext().registerWithGeneratedName(accProxyBdb.getBeanDefinition());
}

From source file:org.rosenvold.spring.convention.ConventionBeanFactory.java

private void registerBeanByResolvedType(String beanName, Class<?> resolvedType) {
    if (resolvedType == null)
        return;//from   ww  w  .j  a v  a 2s.  co m
    final BeanDefinition beanDefinition = getOrCreateBeanDefinition(beanName, resolvedType);
    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
    ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(beanDefinition);

    ScopedProxyMode scopedProxyMode = scopeMetadata.getScopedProxyMode();
    if (!scopedProxyMode.equals(ScopedProxyMode.NO)) {
        definitionHolder = ScopedProxyUtils.createScopedProxy(definitionHolder, this,
                scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS));
    }
    registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/**
 * Prepares Spring context.// ww  w  . j a  v  a 2s. co m
 *
 * @param excludedProps Properties to be excluded.
 * @return application context.
 */
private static GenericApplicationContext prepareSpringContext(final String... excludedProps) {
    GenericApplicationContext springCtx = new GenericApplicationContext();

    if (excludedProps.length > 0) {
        final List<String> excludedPropsList = Arrays.asList(excludedProps);

        BeanFactoryPostProcessor postProc = new BeanFactoryPostProcessor() {
            /**
             * @param def Registered BeanDefinition.
             * @throws BeansException in case of errors.
             */
            private void processNested(BeanDefinition def) throws BeansException {
                Iterator<PropertyValue> iterVals = def.getPropertyValues().getPropertyValueList().iterator();

                while (iterVals.hasNext()) {
                    PropertyValue val = iterVals.next();

                    if (excludedPropsList.contains(val.getName())) {
                        iterVals.remove();

                        continue;
                    }

                    if (val.getValue() instanceof Iterable) {
                        Iterator iterNested = ((Iterable) val.getValue()).iterator();

                        while (iterNested.hasNext()) {
                            Object item = iterNested.next();

                            if (item instanceof BeanDefinitionHolder) {
                                BeanDefinitionHolder h = (BeanDefinitionHolder) item;

                                try {
                                    if (h.getBeanDefinition().getBeanClassName() != null)
                                        Class.forName(h.getBeanDefinition().getBeanClassName());

                                    processNested(h.getBeanDefinition());
                                } catch (ClassNotFoundException ignored) {
                                    iterNested.remove();
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
                    throws BeansException {
                for (String beanName : beanFactory.getBeanDefinitionNames()) {
                    try {
                        BeanDefinition def = beanFactory.getBeanDefinition(beanName);

                        if (def.getBeanClassName() != null)
                            Class.forName(def.getBeanClassName());

                        processNested(def);
                    } catch (ClassNotFoundException ignored) {
                        ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName);
                    }
                }
            }
        };

        springCtx.addBeanFactoryPostProcessor(postProc);
    }

    return springCtx;
}

From source file:org.blocks4j.feature.toggle.spring.scheme.FeatureToggleDefinitionParser.java

@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext context) {
    AbstractBeanDefinition result = null;
    if (DomUtils.nodeNameEquals(element, TAG_TOGGLE_NAME)) {
        BeanDefinitionHolder holder = context.getDelegate().parseBeanDefinitionElement(element);
        result = (AbstractBeanDefinition) holder.getBeanDefinition();

        String feature = element.getAttribute(TAG_FEATURE_NAME);
        String commonInterfaceName = element.getAttribute(TAG_COMMON_INTERFACE_NAME);
        String onRefName = element.getAttribute(TAG_ON_REF_NAME);
        String offRefName = element.getAttribute(TAG_OFF_REF_NAME);

        if (StringUtils.isEmpty(onRefName)) {
            throw new FeatureToggleDefinitionParsingException("You must specify on-ref");
        }/*from   w  ww.j  av a  2 s  . c  o m*/
        if (StringUtils.isEmpty(offRefName)) {
            throw new FeatureToggleDefinitionParsingException("You must specify on-ref");
        }
        Class<?> commonInterface;
        try {
            commonInterface = Class.forName(commonInterfaceName);
        } catch (Exception e) {
            LOGGER.error("It was not possible to find interface of type '{}'", commonInterfaceName);
            throw new FeatureToggleDefinitionParsingException(
                    String.format("It was not possible to find interface of type '%s'", commonInterfaceName),
                    e);
        }
        String fbeanName = feature.concat("_" + this.randomUUID() + "_factory");
        this.buildNewFactoryBean(fbeanName, context, onRefName, offRefName, commonInterface, feature);
        result.setFactoryBeanName(fbeanName);
        result.setFactoryMethodName(TAG_TOGGLE_NAME);
        context.getRegistry()
                .registerBeanDefinition(TAG_TOGGLE_NAME.concat(Integer.toHexString(this.hashCode())), result);
    }
    return result;
}

From source file:org.devproof.portal.core.config.factory.DevproofClassPathBeanDefinitionScanner.java

@Override
protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
    try {//from w  ww  .j  a v  a 2  s  .com
        @SuppressWarnings({ "unchecked" })
        Class<? extends Page> clazz = (Class<? extends Page>) Class
                .forName(definitionHolder.getBeanDefinition().getBeanClassName());
        if (clazz.isAnnotationPresent(ModulePage.class)) {
            moduleConfiguration.addPageConfiguration(new PageConfiguration(clazz));
        } else if (clazz.isAnnotationPresent(NavigationBox.class)) {
            moduleConfiguration.addBox(new BoxConfiguration(clazz));
        } else if (clazz.isAnnotationPresent(GenericRepository.class)) {
            BeanDefinitionHolder beanDefinitionHolder = buildGenericRepositoryDefinition(clazz);
            super.registerBeanDefinition(beanDefinitionHolder, registry);
        } else if (clazz.isAnnotationPresent(Entity.class)
                || clazz.isAnnotationPresent(org.hibernate.annotations.Entity.class)) {
            moduleConfiguration.addEntity(clazz);
            if (clazz.isAnnotationPresent(RegisterGenericDataProvider.class)) {
                BeanDefinitionHolder beanDefinitionHolder = buildGenericDataProviderDefinition(clazz);
                super.registerBeanDefinition(beanDefinitionHolder, registry);
            }
        } else {
            super.registerBeanDefinition(definitionHolder, registry);
        }

    } catch (ClassNotFoundException e) {
        logger.fatal(e);
    }
}

From source file:org.eclipse.gemini.blueprint.blueprint.config.internal.BlueprintParser.java

public BeanDefinitionHolder parseAsHolder(Element componentElement, ParserContext parserContext) {
    // save parser context
    this.parserContext = parserContext;
    this.defaults = new BlueprintDefaultsDefinition(componentElement.getOwnerDocument(), parserContext);

    // let Spring do its standard parsing
    BeanDefinitionHolder bdHolder = parseComponentDefinitionElement(componentElement, null);

    BeanDefinition bd = bdHolder.getBeanDefinition();
    if (bd != null) {
        bd.setAttribute(ParsingUtils.BLUEPRINT_MARKER_NAME, Boolean.TRUE);
    }/*from  ww w  .j  a  va2 s  .  co  m*/

    return bdHolder;
}

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
 *//*  www  .  j  a v  a 2s.  c  om*/
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
 *///from ww  w  . j  a v a 2s  .  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;
}