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

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

Introduction

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

Prototype

public void addGenericArgumentValue(ValueHolder newValue) 

Source Link

Document

Add a generic argument value to be matched by type or name (if available).

Usage

From source file:ome.client.utests.Preferences3Test.java

@Test(groups = "ticket:1058")
public void testOmeroUserIsProperlySetWithSpring2_5_5Manual() {

    Server s = new Server("localhost", 1099);
    Login l = new Login("me", "password");
    Properties p = s.asProperties();
    p.putAll(l.asProperties());//from w  ww.jav  a 2s .  co  m

    // This is copied from OmeroContext. This is the parent context which
    // should contain the properties;
    Properties copy = new Properties(p);
    ConstructorArgumentValues ctorArg1 = new ConstructorArgumentValues();
    ctorArg1.addGenericArgumentValue(copy);
    BeanDefinition definition1 = new RootBeanDefinition(Properties.class, ctorArg1, null);
    StaticApplicationContext staticContext = new StaticApplicationContext();
    staticContext.registerBeanDefinition("properties", definition1);
    staticContext.refresh();

    // This is the child context and contains a definition of a
    // PlaceHolderConfigurer
    // as well as a user of
    StaticApplicationContext childContext = new StaticApplicationContext();

    MutablePropertyValues mpv2 = new MutablePropertyValues();
    mpv2.addPropertyValue("properties", new RuntimeBeanReference("properties"));
    mpv2.addPropertyValue("systemPropertiesModeName", "SYSTEM_PROPERTIES_MODE_FALLBACK");
    mpv2.addPropertyValue("localOverride", "true");
    BeanDefinition definitionConfigurer = new RootBeanDefinition(PreferencesPlaceholderConfigurer.class, null,
            mpv2);
    childContext.registerBeanDefinition("propertiesPlaceholderConfigurer", definitionConfigurer);

    ConstructorArgumentValues cav2 = new ConstructorArgumentValues();
    cav2.addGenericArgumentValue("${omero.user}");
    BeanDefinition definitionTest = new RootBeanDefinition(String.class, cav2, null);
    childContext.registerBeanDefinition("test", definitionTest);

    childContext.setParent(staticContext);
    childContext.refresh();

    String test = (String) childContext.getBean("test");
    assertEquals(test, "me");

}

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  w  w .j  a va  2  s .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.springframework.beans.factory.DefaultListableBeanFactoryTests.java

/**
 * @param singleton whether the bean created from the factory method on
 * the bean instance should be a singleton or prototype. This flag is
 * used to allow checking of the new ability in 1.2.4 to determine the type
 * of a prototype created from invoking a factory method on a bean instance
 * in the factory.//  www .  j  ava 2 s.c  o m
 */
private void findTypeOfPrototypeFactoryMethodOnBeanInstance(boolean singleton) {
    String expectedNameFromProperties = "tony";
    String expectedNameFromArgs = "gordon";

    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition instanceFactoryDefinition = new RootBeanDefinition(BeanWithFactoryMethod.class);
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("name", expectedNameFromProperties);
    instanceFactoryDefinition.setPropertyValues(pvs);
    lbf.registerBeanDefinition("factoryBeanInstance", instanceFactoryDefinition);

    RootBeanDefinition factoryMethodDefinitionWithProperties = new RootBeanDefinition();
    factoryMethodDefinitionWithProperties.setFactoryBeanName("factoryBeanInstance");
    factoryMethodDefinitionWithProperties.setFactoryMethodName("create");
    if (!singleton) {
        factoryMethodDefinitionWithProperties.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    }
    lbf.registerBeanDefinition("fmWithProperties", factoryMethodDefinitionWithProperties);

    RootBeanDefinition factoryMethodDefinitionGeneric = new RootBeanDefinition();
    factoryMethodDefinitionGeneric.setFactoryBeanName("factoryBeanInstance");
    factoryMethodDefinitionGeneric.setFactoryMethodName("createGeneric");
    if (!singleton) {
        factoryMethodDefinitionGeneric.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    }
    lbf.registerBeanDefinition("fmGeneric", factoryMethodDefinitionGeneric);

    RootBeanDefinition factoryMethodDefinitionWithArgs = new RootBeanDefinition();
    factoryMethodDefinitionWithArgs.setFactoryBeanName("factoryBeanInstance");
    factoryMethodDefinitionWithArgs.setFactoryMethodName("createWithArgs");
    ConstructorArgumentValues cvals = new ConstructorArgumentValues();
    cvals.addGenericArgumentValue(expectedNameFromArgs);
    factoryMethodDefinitionWithArgs.setConstructorArgumentValues(cvals);
    if (!singleton) {
        factoryMethodDefinitionWithArgs.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    }
    lbf.registerBeanDefinition("fmWithArgs", factoryMethodDefinitionWithArgs);

    assertEquals(4, lbf.getBeanDefinitionCount());
    List<String> tbNames = Arrays.asList(lbf.getBeanNamesForType(TestBean.class));
    assertTrue(tbNames.contains("fmWithProperties"));
    assertTrue(tbNames.contains("fmWithArgs"));
    assertEquals(2, tbNames.size());

    TestBean tb = (TestBean) lbf.getBean("fmWithProperties");
    TestBean second = (TestBean) lbf.getBean("fmWithProperties");
    if (singleton) {
        assertSame(tb, second);
    } else {
        assertNotSame(tb, second);
    }
    assertEquals(expectedNameFromProperties, tb.getName());

    tb = (TestBean) lbf.getBean("fmGeneric");
    second = (TestBean) lbf.getBean("fmGeneric");
    if (singleton) {
        assertSame(tb, second);
    } else {
        assertNotSame(tb, second);
    }
    assertEquals(expectedNameFromProperties, tb.getName());

    TestBean tb2 = (TestBean) lbf.getBean("fmWithArgs");
    second = (TestBean) lbf.getBean("fmWithArgs");
    if (singleton) {
        assertSame(tb2, second);
    } else {
        assertNotSame(tb2, second);
    }
    assertEquals(expectedNameFromArgs, tb2.getName());
}

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

/**
 * Resolve the constructor arguments for this bean into the resolvedValues object.
 * This may involve looking up other beans.
 * <p>This method is also used for handling invocations of static factory methods.
 *///  ww w  . j  a v a 2 s .c  o  m
private int resolveConstructorArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
        ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {

    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd,
            converter);

    int minNrOfArgs = cargs.getArgumentCount();

    for (Map.Entry<Integer, ConstructorArgumentValues.ValueHolder> entry : cargs.getIndexedArgumentValues()
            .entrySet()) {
        int index = entry.getKey();
        if (index < 0) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Invalid constructor argument index: " + index);
        }
        if (index > minNrOfArgs) {
            minNrOfArgs = index + 1;
        }
        ConstructorArgumentValues.ValueHolder valueHolder = entry.getValue();
        if (valueHolder.isConverted()) {
            resolvedValues.addIndexedArgumentValue(index, valueHolder);
        } else {
            Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument",
                    valueHolder.getValue());
            ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(
                    resolvedValue, valueHolder.getType(), valueHolder.getName());
            resolvedValueHolder.setSource(valueHolder);
            resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder);
        }
    }

    for (ConstructorArgumentValues.ValueHolder valueHolder : cargs.getGenericArgumentValues()) {
        if (valueHolder.isConverted()) {
            resolvedValues.addGenericArgumentValue(valueHolder);
        } else {
            Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument",
                    valueHolder.getValue());
            ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(
                    resolvedValue, valueHolder.getType(), valueHolder.getName());
            resolvedValueHolder.setSource(valueHolder);
            resolvedValues.addGenericArgumentValue(resolvedValueHolder);
        }
    }

    return minNrOfArgs;
}

From source file:org.springframework.cloud.function.context.config.KotlinLambdaToFunctionAutoConfiguration.java

/**
 * Will transform all discovered Kotlin's Function1 and Function0 lambdas to java
 * Supplier, Function and Consumer, retaining the original Kotlin type
 * characteristics. In other words the resulting bean could be cast to both java and
 * kotlin types (i.e., java Function&lt;I,O&gt; vs. kotlin Function1&lt;I,O&gt;)
 * @return the bean factory post processor
 *//*from   w ww . j  av a2  s  . co m*/
@Bean
public BeanFactoryPostProcessor kotlinToFunctionTransformer() {
    return new BeanFactoryPostProcessor() {

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String beanDefinitionName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
                Object source = beanDefinition.getSource();
                if (source instanceof MethodMetadata) {
                    String returnTypeName = ((MethodMetadata) source).getReturnTypeName();
                    if (returnTypeName.startsWith("kotlin.jvm.functions.Function")) {
                        FunctionType functionType = new FunctionType(
                                FunctionContextUtils.findType(beanDefinitionName, beanFactory));
                        if (returnTypeName.equals("kotlin.jvm.functions.Function1")) {
                            if (Unit.class.isAssignableFrom(functionType.getOutputType())) {
                                KotlinLambdaToFunctionAutoConfiguration.this.logger
                                        .debug("Transforming Kotlin lambda " + beanDefinitionName
                                                + " to java Consumer");
                                this.register(beanDefinitionName, beanDefinition, KotlinConsumer.class,
                                        (BeanDefinitionRegistry) beanFactory);
                            } else {
                                KotlinLambdaToFunctionAutoConfiguration.this.logger
                                        .debug("Transforming Kotlin lambda " + beanDefinitionName
                                                + " to java Function");
                                this.register(beanDefinitionName, beanDefinition, KotlinFunction.class,
                                        (BeanDefinitionRegistry) beanFactory);
                            }
                        } else {
                            KotlinLambdaToFunctionAutoConfiguration.this.logger.debug(
                                    "Transforming Kotlin lambda " + beanDefinitionName + " to java Supplier");
                            this.register(beanDefinitionName, beanDefinition, KotlinSupplier.class,
                                    (BeanDefinitionRegistry) beanFactory);
                        }
                    }
                }
            }
        }

        private void register(String originalName, BeanDefinition originalDefinition, Class<?> clazz,
                BeanDefinitionRegistry registry) {
            RootBeanDefinition cbd = new RootBeanDefinition(clazz);
            ConstructorArgumentValues ca = new ConstructorArgumentValues();
            ca.addGenericArgumentValue(originalDefinition);
            cbd.setConstructorArgumentValues(ca);
            registry.removeBeanDefinition(originalName);
            registry.registerBeanDefinition(originalName, cbd);
        }
    };
}