Example usage for org.springframework.beans.factory.config ConstructorArgumentValues addIndexedArgumentValue

List of usage examples for org.springframework.beans.factory.config ConstructorArgumentValues addIndexedArgumentValue

Introduction

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

Prototype

public void addIndexedArgumentValue(int index, ValueHolder newValue) 

Source Link

Document

Add an argument value for the given index in the constructor argument list.

Usage

From source file:org.jsr107.ri.annotations.spring.config.AnnotationDrivenJCacheBeanDefinitionParser.java

/**
 * Create a {@link CacheContextSourceImpl} bean that will be used by the advisor and interceptor
 *
 * @return Reference to the {@link CacheContextSourceImpl}. Should never be null.
 */// www  .  j  av  a  2 s .c om
protected RuntimeBeanReference setupCacheOperationSource(Element element, ParserContext parserContext,
        Object elementSource) {

    final RootBeanDefinition cacheAttributeSource = new RootBeanDefinition(CacheContextSourceImpl.class);
    cacheAttributeSource.setSource(elementSource);
    cacheAttributeSource.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

    final RootBeanDefinition defaultCacheResolverFactory = new RootBeanDefinition(
            DefaultCacheResolverFactory.class);
    cacheAttributeSource.setSource(elementSource);
    cacheAttributeSource.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    final String cacheManagerName = element.getAttribute(XSD_ATTR_CACHE_MANAGER);
    if (StringUtils.hasText(cacheManagerName)) {
        final RuntimeBeanReference cacheManagerReference = new RuntimeBeanReference(cacheManagerName);

        final ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
        constructorArgumentValues.addIndexedArgumentValue(0, cacheManagerReference);
        cacheAttributeSource.setConstructorArgumentValues(constructorArgumentValues);

    }

    final RootBeanDefinition defaultCacheKeyGenerator = new RootBeanDefinition(DefaultCacheKeyGenerator.class);
    cacheAttributeSource.setSource(elementSource);
    cacheAttributeSource.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

    final MutablePropertyValues propertyValues = cacheAttributeSource.getPropertyValues();
    propertyValues.addPropertyValue("defaultCacheKeyGenerator", defaultCacheKeyGenerator);
    propertyValues.addPropertyValue("defaultCacheResolverFactory", defaultCacheResolverFactory);

    final BeanDefinitionRegistry registry = parserContext.getRegistry();
    registry.registerBeanDefinition(JCACHE_CACHE_OPERATION_SOURCE_BEAN_NAME, cacheAttributeSource);

    return new RuntimeBeanReference(JCACHE_CACHE_OPERATION_SOURCE_BEAN_NAME);
}

From source file:org.romaz.spring.scripting.ext.ExtScriptBeanDefinitionParser.java

/**
 * Parses the dynamic object element and returns the resulting bean definition.
 * Registers a {@link ScriptFactoryPostProcessor} if needed.
 */// w w  w  .java 2 s . c o m
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    // Resolve the script source.
    String value = resolveScriptSource(element, parserContext.getReaderContext());
    if (value == null) {
        return null;
    }

    // Set up infrastructure.
    LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());

    // Create script factory bean definition.
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClassName(this.scriptFactoryClassName);
    bd.setSource(parserContext.extractSource(element));

    // Determine bean scope.
    String scope = element.getAttribute(SCOPE_ATTRIBUTE);
    if (StringUtils.hasLength(scope)) {
        bd.setScope(scope);
    }

    // Determine autowire mode.
    String autowire = element.getAttribute(AUTOWIRE_ATTRIBUTE);
    int autowireMode = parserContext.getDelegate().getAutowireMode(autowire);
    // Only "byType" and "byName" supported, but maybe other default inherited...
    if (autowireMode == GenericBeanDefinition.AUTOWIRE_AUTODETECT) {
        autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE;
    } else if (autowireMode == GenericBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
        autowireMode = GenericBeanDefinition.AUTOWIRE_NO;
    }
    bd.setAutowireMode(autowireMode);

    // Determine dependency check setting.
    String dependencyCheck = element.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE);
    bd.setDependencyCheck(parserContext.getDelegate().getDependencyCheck(dependencyCheck));

    // Retrieve the defaults for bean definitions within this parser context
    BeanDefinitionDefaults beanDefinitionDefaults = parserContext.getDelegate().getBeanDefinitionDefaults();

    // Determine init method and destroy method.
    String initMethod = element.getAttribute(INIT_METHOD_ATTRIBUTE);
    if (StringUtils.hasLength(initMethod)) {
        bd.setInitMethodName(initMethod);
    } else if (beanDefinitionDefaults.getInitMethodName() != null) {
        bd.setInitMethodName(beanDefinitionDefaults.getInitMethodName());
    }

    String destroyMethod = element.getAttribute(DESTROY_METHOD_ATTRIBUTE);
    if (StringUtils.hasLength(destroyMethod)) {
        bd.setDestroyMethodName(destroyMethod);
    } else if (beanDefinitionDefaults.getDestroyMethodName() != null) {
        bd.setDestroyMethodName(beanDefinitionDefaults.getDestroyMethodName());
    }

    // Attach any refresh metadata.
    String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
    if (StringUtils.hasText(refreshCheckDelay)) {
        bd.setAttribute(ScriptFactoryPostProcessor.REFRESH_CHECK_DELAY_ATTRIBUTE, new Long(refreshCheckDelay));
    }

    // Add constructor arguments.
    ConstructorArgumentValues cav = bd.getConstructorArgumentValues();
    int constructorArgNum = 0;
    cav.addIndexedArgumentValue(constructorArgNum++, value);
    if (element.hasAttribute(SCRIPT_INTERFACES_ATTRIBUTE)) {
        cav.addIndexedArgumentValue(constructorArgNum++, element.getAttribute(SCRIPT_INTERFACES_ATTRIBUTE));
    }
    if (element.hasAttribute(SCRIPT_CONFIG_ATTRIBUTE)) {
        cav.addIndexedArgumentValue(constructorArgNum++,
                new RuntimeBeanReference(element.getAttribute(SCRIPT_CONFIG_ATTRIBUTE)));
    }
    // Add any property definitions that need adding.
    parserContext.getDelegate().parsePropertyElements(element, bd);

    return bd;
}

From source file:com.capgemini.boot.core.factory.internal.SettingBackedBeanFactoryPostProcessor.java

private BeanDefinition createBeanDefinition(Object settings, Object setting, String factoryBeanName,
        Method factoryMethod) {/*from ww  w .jav  a  2 s .  c  o m*/
    final GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setFactoryBeanName(factoryBeanName);
    definition.setFactoryMethodName(factoryMethod.getName());

    //Create method arguments (confusingly called constructor arguments in spring)
    final ConstructorArgumentValues arguments = new ConstructorArgumentValues();
    arguments.addIndexedArgumentValue(0, setting);

    final int parameterCount = factoryMethod.getParameterTypes().length;
    if (parameterCount == 2) {
        arguments.addIndexedArgumentValue(1, settings);
    } else if (parameterCount > 2) {
        throw getExceptionFactory().createInvalidArgumentsException(factoryMethod);
    }

    //TODO more checking of method arguments to ensure they're correct

    definition.setConstructorArgumentValues(arguments);

    return definition;
}

From source file:eap.config.ConfigBeanDefinitionParser.java

/**
 * Creates the RootBeanDefinition for a POJO advice bean. Also causes pointcut
 * parsing to occur so that the pointcut may be associate with the advice bean.
 * This same pointcut is also configured as the pointcut for the enclosing
 * Advisor definition using the supplied MutablePropertyValues.
 *///from w w  w.  j  a va  2  s.  c om
private AbstractBeanDefinition createAdviceDefinition(Element adviceElement, ParserContext parserContext,
        String aspectName, int order, RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef,
        List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {

    RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement, parserContext));
    adviceDefinition.setSource(parserContext.extractSource(adviceElement));

    adviceDefinition.getPropertyValues().add(ASPECT_NAME_PROPERTY, aspectName);
    adviceDefinition.getPropertyValues().add(DECLARATION_ORDER_PROPERTY, order);

    if (adviceElement.hasAttribute(RETURNING)) {
        adviceDefinition.getPropertyValues().add(RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING));
    }
    if (adviceElement.hasAttribute(THROWING)) {
        adviceDefinition.getPropertyValues().add(THROWING_PROPERTY, adviceElement.getAttribute(THROWING));
    }
    if (adviceElement.hasAttribute(ARG_NAMES)) {
        adviceDefinition.getPropertyValues().add(ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES));
    }

    ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues();
    cav.addIndexedArgumentValue(METHOD_INDEX, methodDef);

    Object pointcut = parsePointcutProperty(adviceElement, parserContext);
    if (pointcut instanceof BeanDefinition) {
        cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut);
        beanDefinitions.add((BeanDefinition) pointcut);
    } else if (pointcut instanceof String) {
        RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut);
        cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef);
        beanReferences.add(pointcutRef);
    }

    cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef);

    return adviceDefinition;
}

From source file:org.solmix.runtime.support.spring.ContainerPostProcessor.java

private void insertConstructorArg(ConstructorArgumentValues constructorArgs, Object valueToInsert) {
    List<ValueHolder> genericArgs = new ArrayList<ValueHolder>((constructorArgs.getGenericArgumentValues()));
    Map<Integer, ValueHolder> indexedArgs = new HashMap<Integer, ValueHolder>(
            constructorArgs.getIndexedArgumentValues());

    constructorArgs.clear();/*from   ww  w .j av a2  s.  c o m*/
    for (ValueHolder genericValue : genericArgs) {
        constructorArgs.addGenericArgumentValue(genericValue);
    }
    for (Map.Entry<Integer, ValueHolder> entry : indexedArgs.entrySet()) {
        constructorArgs.addIndexedArgumentValue(entry.getKey() + 1, entry.getValue());
    }
    constructorArgs.addIndexedArgumentValue(0, valueToInsert);
}

From source file:com.fitbur.testify.di.spring.SpringServiceLocator.java

@Override
public void addService(ServiceDescriptor descriptor) {
    checkState(!context.containsBeanDefinition(descriptor.getName()),
            "Service with the name '%s' already exists.", descriptor.getName());

    GenericBeanDefinition bean = new GenericBeanDefinition();
    bean.setBeanClass(descriptor.getType());
    bean.setAutowireCandidate(descriptor.getDiscoverable());
    bean.setPrimary(descriptor.getPrimary());
    bean.setLazyInit(descriptor.getLazy());
    bean.setRole(ROLE_APPLICATION);/*  w  ww.  j a va  2 s  .c  o  m*/

    if (descriptor.getInjectable()) {
        bean.setAutowireMode(AUTOWIRE_CONSTRUCTOR);
    } else {
        bean.setAutowireMode(AUTOWIRE_NO);
        ConstructorArgumentValues values = new ConstructorArgumentValues();

        Object[] arguments = descriptor.getArguments();
        for (int i = 0; i < arguments.length; i++) {
            Object arg = arguments[i];

            if (arg == null) {
                //TODO: warn user that the argument was not specified and there
                //for the real instance will be injected.
                continue;
            }

            values.addIndexedArgumentValue(i, arg);
        }

        bean.setConstructorArgumentValues(values);
    }

    ServiceScope scope = descriptor.getScope();
    switch (scope) {
    case PROTOTYPE:
        bean.setScope("prototype");
        break;
    case SINGLETON:
        bean.setScope("singleton");
        break;
    case REQUEST:
        bean.setScope("request");
        break;
    case SESSION:
        bean.setScope("session");
        break;
    case APPLICATION:
        bean.setScope("application");
        break;
    default:
        checkState(false, "Scope '{}' is not supported by Spring IoC.", scope.name());

    }
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
    beanFactory.registerBeanDefinition(descriptor.getName(), bean);
}

From source file:org.constretto.spring.ConfigurationAnnotationConfigurer.java

@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
        final Class<?> beanType = beanFactory.getType(beanName);
        if (!configurableConstructorCache.containsKey(beanType)) {
            configurableConstructorCache.put(beanType, resolveConfigurableConstructor(beanType));
        }/*from  w  w w .j  a v  a 2  s  .com*/
        final Constructor<?> resolvedConstructor = configurableConstructorCache.get(beanType);
        if (resolvedConstructor != null) {
            final ConstructorArgumentValues constructorArgumentValues = beanDefinition
                    .getConstructorArgumentValues();
            final ArgumentDescription[] argumentDescriptions = ArgumentDescriptionFactory
                    .create(resolvedConstructor).resolveParameters();
            for (int i = 0; i < argumentDescriptions.length; i++) {
                ArgumentDescription argumentDescription = argumentDescriptions[i];
                if (!constructorArgumentValues.hasIndexedArgumentValue(i)) {
                    final String keyName = argumentDescription.constrettoConfigurationKeyCandidate();
                    if (configuration.hasValue(keyName)) {
                        constructorArgumentValues.addIndexedArgumentValue(i,
                                configuration.evaluateTo(argumentDescription.getType(), keyName));
                    }
                }
            }
        }

    }
}

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

private void parseConstructorArgElement(Element ele, AbstractBeanDefinition beanDefinition) {

    String indexAttr = ele.getAttribute(BeanDefinitionParserDelegate.INDEX_ATTRIBUTE);
    String typeAttr = ele.getAttribute(BeanDefinitionParserDelegate.TYPE_ATTRIBUTE);

    boolean hasIndex = false;
    int index = -1;

    if (StringUtils.hasLength(indexAttr)) {
        hasIndex = true;/*from   w  ww. jav a 2s. c  o m*/
        try {
            index = Integer.parseInt(indexAttr);
        } catch (NumberFormatException ex) {
            error("Attribute 'index' of tag 'constructor-arg' must be an integer", ele);
        }

        if (index < 0) {
            error("'index' cannot be lower than 0", ele);
        }
    }

    try {
        this.parseState.push(hasIndex ? new ConstructorArgumentEntry(index) : new ConstructorArgumentEntry());

        ConstructorArgumentValues values = beanDefinition.getConstructorArgumentValues();
        // Blueprint failure (index duplication)
        Integer indexInt = Integer.valueOf(index);
        if (values.getIndexedArgumentValues().containsKey(indexInt)) {
            error("duplicate 'index' with value=[" + index + "] specified", ele);
        }

        Object value = parsePropertyValue(ele, beanDefinition, null);
        ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
        if (StringUtils.hasLength(typeAttr)) {
            valueHolder.setType(typeAttr);
        }
        valueHolder.setSource(extractSource(ele));

        if (hasIndex) {
            values.addIndexedArgumentValue(index, valueHolder);
        } else {
            values.addGenericArgumentValue(valueHolder);
        }
        // Blueprint failure (mixed index/non-indexed arguments)
        if (!values.getGenericArgumentValues().isEmpty() && !values.getIndexedArgumentValues().isEmpty()) {
            error("indexed and non-indexed constructor arguments are not supported by Blueprint; "
                    + "consider using the Spring namespace instead", ele);
        }
    } finally {
        this.parseState.pop();
    }
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.BlueprintContainerProcessor.java

public void preProcessRefresh(final ConfigurableOsgiBundleApplicationContext context) {
    final BundleContext bundleContext = context.getBundleContext();
    // create the ModuleContext adapter
    final BlueprintContainer blueprintContainer = createBlueprintContainer(context);

    // 1. add event listeners
    // add service publisher
    context.addApplicationListener(new BlueprintContainerServicePublisher(blueprintContainer, bundleContext));
    // add waiting event broadcaster
    context.addApplicationListener(new BlueprintWaitingEventDispatcher(context.getBundleContext()));

    // 2. add environmental managers
    context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {

        private static final String BLUEPRINT_BUNDLE = "blueprintBundle";
        private static final String BLUEPRINT_BUNDLE_CONTEXT = "blueprintBundleContext";
        private static final String BLUEPRINT_CONTAINER = "blueprintContainer";
        private static final String BLUEPRINT_EXTENDER = "blueprintExtenderBundle";
        private static final String BLUEPRINT_CONVERTER = "blueprintConverter";

        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            // lazy logger evaluation
            Log logger = LogFactory.getLog(context.getClass());

            if (!(beanFactory instanceof BeanDefinitionRegistry)) {
                logger.warn("Environmental beans will be registered as singletons instead "
                        + "of usual bean definitions since beanFactory " + beanFactory
                        + " is not a BeanDefinitionRegistry");
            }//from  w  ww .ja va 2 s  . c  om

            // add blueprint container bean
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_BUNDLE, bundleContext.getBundle(), logger);
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_BUNDLE_CONTEXT, bundleContext, logger);
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_CONTAINER, blueprintContainer, logger);
            // addPredefinedBlueprintBean(beanFactory, BLUEPRINT_EXTENDER, extenderBundle, logger);
            addPredefinedBlueprintBean(beanFactory, BLUEPRINT_CONVERTER,
                    new SpringBlueprintConverter(beanFactory), logger);

            // add Blueprint conversion service
            // String[] beans = beanFactory.getBeanNamesForType(BlueprintConverterConfigurer.class, false, false);
            // if (ObjectUtils.isEmpty(beans)) {
            // beanFactory.addPropertyEditorRegistrar(new BlueprintEditorRegistrar());
            // }
            beanFactory.setConversionService(
                    new SpringBlueprintConverterService(beanFactory.getConversionService(), beanFactory));
        }

        private void addPredefinedBlueprintBean(ConfigurableListableBeanFactory beanFactory, String beanName,
                Object value, Log logger) {
            if (!beanFactory.containsLocalBean(beanName)) {
                logger.debug("Registering pre-defined bean named " + beanName);
                if (beanFactory instanceof BeanDefinitionRegistry) {
                    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

                    GenericBeanDefinition def = new GenericBeanDefinition();
                    def.setBeanClass(ENV_FB_CLASS);
                    ConstructorArgumentValues cav = new ConstructorArgumentValues();
                    cav.addIndexedArgumentValue(0, value);
                    def.setConstructorArgumentValues(cav);
                    def.setLazyInit(false);
                    def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
                    registry.registerBeanDefinition(beanName, def);

                } else {
                    beanFactory.registerSingleton(beanName, value);
                }

            } else {
                logger.warn("A bean named " + beanName
                        + " already exists; aborting registration of the predefined value...");
            }
        }
    });

    // 3. add cycle breaker
    context.addBeanFactoryPostProcessor(cycleBreaker);

    BlueprintEvent creatingEvent = new BlueprintEvent(BlueprintEvent.CREATING, context.getBundle(),
            extenderBundle);
    listenerManager.blueprintEvent(creatingEvent);
    dispatcher.beforeRefresh(creatingEvent);
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testCustomTypeConverter() {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
    lbf.setTypeConverter(new CustomTypeConverter(nf));
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("myFloat", "1,1");
    ConstructorArgumentValues cav = new ConstructorArgumentValues();
    cav.addIndexedArgumentValue(0, "myName");
    cav.addIndexedArgumentValue(1, "myAge");
    lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, cav, pvs));
    TestBean testBean = (TestBean) lbf.getBean("testBean");
    assertEquals("myName", testBean.getName());
    assertEquals(5, testBean.getAge());/*from ww w  .java  2s  . c o  m*/
    assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}