Example usage for org.springframework.beans.factory.support BeanDefinitionReaderUtils createBeanDefinition

List of usage examples for org.springframework.beans.factory.support BeanDefinitionReaderUtils createBeanDefinition

Introduction

In this page you can find the example usage for org.springframework.beans.factory.support BeanDefinitionReaderUtils createBeanDefinition.

Prototype

public static AbstractBeanDefinition createBeanDefinition(@Nullable String parentName,
        @Nullable String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException 

Source Link

Document

Create a new GenericBeanDefinition for the given parent name and class name, eagerly loading the bean class if a ClassLoader has been specified.

Usage

From source file:edu.jhuapl.openessence.config.DataSourceLoader.java

/**
 * @param existingDataSources this can't be injected because the code that initializes the data sources delegates to
 *                            this method
 * @return returns dataSources argument, for chaining
 * @see AppConfig#dataSources()//ww  w  .j a v  a  2 s  .c  o m
 */
public ConcurrentMap<String, JdbcOeDataSource> loadDataSources(
        ConcurrentMap<String, JdbcOeDataSource> existingDataSources) {
    try {
        URL groovyRoot = resourcePatternResolver.getResource("classpath:/ds").getURL();
        Resource[] groovyResources = resourcePatternResolver.getResources("classpath:/ds/*.groovy");

        String[] groovyScriptNames = new String[groovyResources.length];
        for (int i = 0; i < groovyResources.length; i++) {
            groovyScriptNames[i] = FilenameUtils.getName(groovyResources[i].getFile().getPath());
        }

        GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(new URL[] { groovyRoot });

        for (String scriptName : groovyScriptNames) {
            try {
                log.info("Loading Groovy script {}", scriptName);
                Class<?> clazz = groovyScriptEngine.loadScriptByName(scriptName);
                JdbcOeDataSource ds = (JdbcOeDataSource) beanFactory.createBean(clazz);

                existingDataSources.put(ds.getDataSourceId(), ds);

                // legacy code expects each DS to be a named bean
                // TODO remove this when legacy code is updated
                try {
                    BeanDefinition beanDef = BeanDefinitionReaderUtils.createBeanDefinition(null,
                            clazz.getName(), groovyScriptEngine.getGroovyClassLoader());
                    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                    registry.registerBeanDefinition(clazz.getName(), beanDef);
                } catch (ClassNotFoundException e) {
                    log.error("Exception creating bean definition for class " + clazz.getName(), e);
                }
            } catch (ResourceException e) {
                // You can have Exception as last param, see http://slf4j.org/faq.html#paramException
                log.error("Exception loading data source {}", scriptName, e);
            } catch (ScriptException e) {
                log.error("Exception loading data source {}", scriptName, e);
            }
        }

        return existingDataSources;
    } catch (BeanDefinitionStoreException e) {
        throw new RuntimeException(e);
    } catch (BeansException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:atunit.spring.SpringContainer.java

protected AbstractBeanDefinition defineAutowireBean(Class<?> type) throws Exception {
    AbstractBeanDefinition beandef = BeanDefinitionReaderUtils.createBeanDefinition(null, type.getName(),
            type.getClassLoader());/*from   w ww.  j  av a2 s  . c  o  m*/
    beandef.setAutowireCandidate(true);
    beandef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_AUTODETECT);
    return beandef;
}

From source file:atunit.spring.SpringContainer.java

protected AbstractBeanDefinition defineInstanceHolderFactoryBean(Class<?> type, Object instance)
        throws Exception {
    ConstructorArgumentValues args = new ConstructorArgumentValues();
    args.addIndexedArgumentValue(0, type);
    args.addIndexedArgumentValue(1, instance);

    AbstractBeanDefinition beandef = BeanDefinitionReaderUtils.createBeanDefinition(null,
            InstanceHolderFactoryBean.class.getName(), getClass().getClassLoader());
    beandef.setConstructorArgumentValues(args);
    beandef.setAutowireCandidate(true);//from   w w w.  ja va 2  s .c  o  m
    return beandef;
}

From source file:com.seovic.validation.config.ValidationBeanDefinitionParser.java

@SuppressWarnings("unchecked")
private BeanDefinition parseValidator(Element element, ParserContext parserContext) {
    String parent = element.getAttribute("parent");
    if ("".equals(parent)) {
        parent = null;//  w  w  w.ja  v a 2 s .c om
    }
    String test = element.getAttribute("test");
    String when = element.getAttribute("when");
    String validateAll = element.getAttribute("validate-all");
    String context = element.getAttribute("context");
    String includeElementsErrors = element.getAttribute("include-element-errors");

    MutablePropertyValues properties = new MutablePropertyValues();
    if (StringUtils.hasText(test)) {
        properties.addPropertyValue("test", test);
    }
    if (StringUtils.hasText(when)) {
        properties.addPropertyValue("when", when);
    }
    if (StringUtils.hasText(validateAll)) {
        properties.addPropertyValue("validateAll", validateAll);
    }
    if (StringUtils.hasText(context)) {
        properties.addPropertyValue("context", context);
    }
    if (StringUtils.hasText(includeElementsErrors)) {
        properties.addPropertyValue("includeElementsErrors", includeElementsErrors);
    }
    ManagedList nestedValidators = new ManagedList();
    ManagedList actions = new ManagedList();
    for (int i = 0; i < element.getChildNodes().getLength(); i++) {
        Node child = element.getChildNodes().item(i);
        if (child != null && child instanceof Element) {
            Element childElement = (Element) child;
            if ("message".equals(childElement.getLocalName())) {
                actions.add(parseErrorMessageAction(childElement, parserContext));
            } else {
                nestedValidators.add(parseAndRegisterValidator2(childElement, parserContext));
            }
        }
    }
    if (nestedValidators.size() > 0) {
        properties.addPropertyValue("validators", nestedValidators);
    }
    if (actions.size() > 0) {
        properties.addPropertyValue("actions", actions);
    }
    String className;
    if ("required".equals(element.getLocalName())) {
        className = RequiredValidator.class.getName();
    } else if ("condition".equals(element.getLocalName())) {
        className = ConditionValidator.class.getName();
    } else if ("validator".equals(element.getLocalName())) {
        className = element.getAttribute("type");
    } else {
        className = ValidatorGroup.class.getName();
    }
    AbstractBeanDefinition validatorDefinition;
    try {
        validatorDefinition = BeanDefinitionReaderUtils.createBeanDefinition(parent, className,
                parserContext.getReaderContext().getBeanClassLoader());
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException("Error occured during creation of bean definition", e);
    }
    validatorDefinition.setResource(parserContext.getReaderContext().getResource());
    validatorDefinition.setSource(parserContext.extractSource(element));
    validatorDefinition.setPropertyValues(properties);
    validatorDefinition.setLazyInit(true);
    validatorDefinition.setScope("singleton");
    return validatorDefinition;
}

From source file:com.seovic.validation.config.ValidationBeanDefinitionParser.java

private static BeanDefinition parseErrorMessageAction(Element message, ParserContext parserContext) {
    String messageId = message.getAttribute("id");
    String[] providers = message.getAttribute("providers").split(",");
    String typeName = ErrorMessageAction.class.getName();

    ConstructorArgumentValues ctorArgs = new ConstructorArgumentValues();
    ctorArgs.addGenericArgumentValue(messageId);
    ctorArgs.addGenericArgumentValue(providers);

    String when = message.getAttribute("when");
    MutablePropertyValues properties = new MutablePropertyValues();
    if (StringUtils.hasText(when)) {
        properties.addPropertyValue("when", when);
    }/*from w  w  w  . j av a  2 s. c  om*/
    AbstractBeanDefinition action;
    try {
        action = BeanDefinitionReaderUtils.createBeanDefinition(null, typeName,
                parserContext.getReaderContext().getBeanClassLoader());
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException("Error occured during creation of bean definition", e);
    }
    action.setConstructorArgumentValues(ctorArgs);
    action.setPropertyValues(properties);
    return action;
}

From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java

protected final <T> T getOrCreateChildBean(Class<T> beanType, String beanClass, Property[] properties) {
    final StringBuilder beanNameBuilder = new StringBuilder();

    beanNameBuilder.append(beanClass);/*from  www  . j  ava 2 s . com*/

    final MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();

    //Sort the properties array first so bean name generation is always consistent
    Arrays.sort(properties, PropertyComparator.INSTANCE);

    for (Property property : properties) {
        final String name = property.name();
        final String value = property.value();
        final String ref = property.ref();

        beanNameBuilder.append("[").append(name).append(",").append(value).append(",").append(ref).append("]");

        if (value.length() > 0) {
            if (ref.length() > 0) {
                throw new IllegalArgumentException(
                        "Only one of value or ref must be specified no both on Property with name: " + name);
            }

            mutablePropertyValues.addPropertyValue(name, value);
        } else if (ref.length() > 0) {
            mutablePropertyValues.addPropertyValue(name, new RuntimeBeanReference(ref));
        } else {
            throw new IllegalArgumentException(
                    "Either value or ref must be specified on Property with name: " + name);
        }
    }

    final String beanName = beanNameBuilder.toString();

    //See if the bean is already registered using the compiled bean name, if so just use that instance
    if (this.childBeanFactory.containsBean(beanName)) {
        return this.childBeanFactory.getBean(beanName, beanType);
    }

    //Create and register the bean if it didn't already exist
    final AbstractBeanDefinition beanDefinition;
    try {
        beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, beanClass,
                ClassUtils.getDefaultClassLoader());
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException(
                "Could not find class '" + beanClass + "' to create " + beanType + " from", e);
    }

    if (ReflectionHelperAware.class.isAssignableFrom(beanDefinition.getBeanClass())) {
        mutablePropertyValues.addPropertyValue("reflectionHelper", this.reflectionHelper);
    }

    beanDefinition.setPropertyValues(mutablePropertyValues);
    this.childBeanFactory.registerBeanDefinition(beanName, beanDefinition);

    return this.childBeanFactory.getBean(beanName, beanType);
}

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

/**
 * Parse the bean definition itself, without regard to name or aliases. May return <code>null</code> if problems
 * occurred during the parse of the bean definition.
 *//*  ww w.  j  ava 2s  .  c  o m*/
private AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName,
        BeanDefinition containingBean) {

    this.parseState.push(new BeanEntry(beanName));

    String className = null;
    if (ele.hasAttribute(BeanDefinitionParserDelegate.CLASS_ATTRIBUTE)) {
        className = ele.getAttribute(BeanDefinitionParserDelegate.CLASS_ATTRIBUTE).trim();
    }

    try {
        AbstractBeanDefinition beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, className,
                parserContext.getReaderContext().getBeanClassLoader());

        // some early validation
        String activation = ele.getAttribute(LAZY_INIT_ATTR);
        String scope = ele.getAttribute(BeanDefinitionParserDelegate.SCOPE_ATTRIBUTE);

        if (EAGER_INIT_VALUE.equals(activation) && BeanDefinition.SCOPE_PROTOTYPE.equals(scope)) {
            error("Prototype beans cannot be eagerly activated", ele);
        }

        // add marker to indicate that the scope was present
        if (StringUtils.hasText(scope)) {
            beanDefinition.setAttribute(DECLARED_SCOPE, Boolean.TRUE);
        }

        // parse attributes
        parseAttributes(ele, beanName, beanDefinition);

        // inner beans get a predefined scope in RFC 124
        if (containingBean != null) {
            beanDefinition.setLazyInit(true);
            beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        }

        // parse description
        beanDefinition.setDescription(
                DomUtils.getChildElementValueByTagName(ele, BeanDefinitionParserDelegate.DESCRIPTION_ELEMENT));

        parseConstructorArgElements(ele, beanDefinition);
        parsePropertyElements(ele, beanDefinition);

        beanDefinition.setResource(parserContext.getReaderContext().getResource());
        beanDefinition.setSource(extractSource(ele));

        return beanDefinition;
    } catch (ClassNotFoundException ex) {
        error("Bean class [" + className + "] not found", ele, ex);
    } catch (NoClassDefFoundError err) {
        error("Class that bean class [" + className + "] depends on not found", ele, err);
    } catch (Throwable ex) {
        error("Unexpected failure during bean definition parsing", ele, ex);
    } finally {
        this.parseState.pop();
    }

    return null;
}

From source file:org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.java

/**
 * Create a bean definition for the given class name and parent name.
 * @param className the name of the bean class
 * @param parentName the name of the bean's parent bean
 * @return the newly created bean definition
 * @throws ClassNotFoundException if bean class resolution was attempted but failed
 *//*from ww w. j  a va2s.  c o m*/
protected AbstractBeanDefinition createBeanDefinition(@Nullable String className, @Nullable String parentName)
        throws ClassNotFoundException {

    return BeanDefinitionReaderUtils.createBeanDefinition(parentName, className,
            this.readerContext.getBeanClassLoader());
}