Search in sources :

Example 36 with MutablePropertyValues

use of org.springframework.beans.MutablePropertyValues in project spring-boot by spring-projects.

the class RelaxedDataBinderTests method testMixedWithUpperCaseWord.

@Test
public void testMixedWithUpperCaseWord() throws Exception {
    // gh-6803
    VanillaTarget target = new VanillaTarget();
    RelaxedDataBinder binder = getBinder(target, "test");
    MutablePropertyValues values = new MutablePropertyValues();
    values.add("test.mixed-u-p-p-e-r", "foo");
    binder.bind(values);
    assertThat(target.getMixedUPPER()).isEqualTo("foo");
}
Also used : MutablePropertyValues(org.springframework.beans.MutablePropertyValues) Test(org.junit.Test)

Example 37 with MutablePropertyValues

use of org.springframework.beans.MutablePropertyValues in project spring-boot by spring-projects.

the class RelaxedDataBinderTests method bind.

private BindingResult bind(DataBinder binder, Object target, String values) throws Exception {
    Properties properties = PropertiesLoaderUtils.loadProperties(new ByteArrayResource(values.getBytes()));
    binder.bind(new MutablePropertyValues(properties));
    binder.validate();
    return binder.getBindingResult();
}
Also used : MutablePropertyValues(org.springframework.beans.MutablePropertyValues) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Properties(java.util.Properties)

Example 38 with MutablePropertyValues

use of org.springframework.beans.MutablePropertyValues in project spring-framework by spring-projects.

the class PropertiesBeanDefinitionReader method registerBeanDefinition.

/**
	 * Get all property values, given a prefix (which will be stripped)
	 * and add the bean they define to the factory with the given name
	 * @param beanName name of the bean to define
	 * @param map Map containing string pairs
	 * @param prefix prefix of each entry, which will be stripped
	 * @param resourceDescription description of the resource that the
	 * Map came from (for logging purposes)
	 * @throws BeansException if the bean definition could not be parsed or registered
	 */
protected void registerBeanDefinition(String beanName, Map<?, ?> map, String prefix, String resourceDescription) throws BeansException {
    String className = null;
    String parent = null;
    String scope = GenericBeanDefinition.SCOPE_SINGLETON;
    boolean isAbstract = false;
    boolean lazyInit = false;
    ConstructorArgumentValues cas = new ConstructorArgumentValues();
    MutablePropertyValues pvs = new MutablePropertyValues();
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        String key = StringUtils.trimWhitespace((String) entry.getKey());
        if (key.startsWith(prefix + SEPARATOR)) {
            String property = key.substring(prefix.length() + SEPARATOR.length());
            if (CLASS_KEY.equals(property)) {
                className = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (PARENT_KEY.equals(property)) {
                parent = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (ABSTRACT_KEY.equals(property)) {
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                isAbstract = TRUE_VALUE.equals(val);
            } else if (SCOPE_KEY.equals(property)) {
                // Spring 2.0 style
                scope = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (SINGLETON_KEY.equals(property)) {
                // Spring 1.2 style
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                scope = ((val == null || TRUE_VALUE.equals(val) ? GenericBeanDefinition.SCOPE_SINGLETON : GenericBeanDefinition.SCOPE_PROTOTYPE));
            } else if (LAZY_INIT_KEY.equals(property)) {
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                lazyInit = TRUE_VALUE.equals(val);
            } else if (property.startsWith(CONSTRUCTOR_ARG_PREFIX)) {
                if (property.endsWith(REF_SUFFIX)) {
                    int index = Integer.parseInt(property.substring(1, property.length() - REF_SUFFIX.length()));
                    cas.addIndexedArgumentValue(index, new RuntimeBeanReference(entry.getValue().toString()));
                } else {
                    int index = Integer.parseInt(property.substring(1));
                    cas.addIndexedArgumentValue(index, readValue(entry));
                }
            } else if (property.endsWith(REF_SUFFIX)) {
                // This isn't a real property, but a reference to another prototype
                // Extract property name: property is of form dog(ref)
                property = property.substring(0, property.length() - REF_SUFFIX.length());
                String ref = StringUtils.trimWhitespace((String) entry.getValue());
                // It doesn't matter if the referenced bean hasn't yet been registered:
                // this will ensure that the reference is resolved at runtime.
                Object val = new RuntimeBeanReference(ref);
                pvs.add(property, val);
            } else {
                // It's a normal bean property.
                pvs.add(property, readValue(entry));
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Registering bean definition for bean name '" + beanName + "' with " + pvs);
    }
    // backwards compatibility reasons.
    if (parent == null && className == null && !beanName.equals(this.defaultParentBean)) {
        parent = this.defaultParentBean;
    }
    try {
        AbstractBeanDefinition bd = BeanDefinitionReaderUtils.createBeanDefinition(parent, className, getBeanClassLoader());
        bd.setScope(scope);
        bd.setAbstract(isAbstract);
        bd.setLazyInit(lazyInit);
        bd.setConstructorArgumentValues(cas);
        bd.setPropertyValues(pvs);
        getRegistry().registerBeanDefinition(beanName, bd);
    } catch (ClassNotFoundException ex) {
        throw new CannotLoadBeanClassException(resourceDescription, beanName, className, ex);
    } catch (LinkageError err) {
        throw new CannotLoadBeanClassException(resourceDescription, beanName, className, err);
    }
}
Also used : ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) HashMap(java.util.HashMap) Map(java.util.Map)

Example 39 with MutablePropertyValues

use of org.springframework.beans.MutablePropertyValues in project spring-framework by spring-projects.

the class AbstractAutowireCapableBeanFactory method populateBean.

/**
	 * Populate the bean instance in the given BeanWrapper with the property values
	 * from the bean definition.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param bw BeanWrapper with bean instance
	 */
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    PropertyValues pvs = mbd.getPropertyValues();
    if (bw == null) {
        if (!pvs.isEmpty()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        } else {
            // Skip property population phase for null instance.
            return;
        }
    }
    // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    // state of the bean before properties are set. This can be used, for example,
    // to support styles of field injection.
    boolean continueWithPropertyPopulation = true;
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }
    if (!continueWithPropertyPopulation) {
        return;
    }
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // Add property values based on autowire by name if applicable.
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
    if (hasInstAwareBpps || needsDepCheck) {
        PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        if (hasInstAwareBpps) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
                        return;
                    }
                }
            }
        }
        if (needsDepCheck) {
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }
    applyPropertyValues(beanName, mbd, bw, pvs);
}
Also used : InstantiationAwareBeanPostProcessor(org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor) SmartInstantiationAwareBeanPostProcessor(org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor) BeanCreationException(org.springframework.beans.factory.BeanCreationException) PropertyValues(org.springframework.beans.PropertyValues) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) PropertyDescriptor(java.beans.PropertyDescriptor) BeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor) InstantiationAwareBeanPostProcessor(org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor) SmartInstantiationAwareBeanPostProcessor(org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor) MutablePropertyValues(org.springframework.beans.MutablePropertyValues)

Example 40 with MutablePropertyValues

use of org.springframework.beans.MutablePropertyValues in project spring-framework by spring-projects.

the class SimplePropertyNamespaceHandler method decorate.

@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
    if (node instanceof Attr) {
        Attr attr = (Attr) node;
        String propertyName = parserContext.getDelegate().getLocalName(attr);
        String propertyValue = attr.getValue();
        MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues();
        if (pvs.contains(propertyName)) {
            parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " + "both <property> and inline syntax. Only one approach may be used per property.", attr);
        }
        if (propertyName.endsWith(REF_SUFFIX)) {
            propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length());
            pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue));
        } else {
            pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue);
        }
    }
    return definition;
}
Also used : MutablePropertyValues(org.springframework.beans.MutablePropertyValues) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) Attr(org.w3c.dom.Attr)

Aggregations

MutablePropertyValues (org.springframework.beans.MutablePropertyValues)305 Test (org.junit.Test)269 TestBean (org.springframework.tests.sample.beans.TestBean)86 ITestBean (org.springframework.tests.sample.beans.ITestBean)82 IndexedTestBean (org.springframework.tests.sample.beans.IndexedTestBean)73 DerivedTestBean (org.springframework.tests.sample.beans.DerivedTestBean)68 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)35 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)24 PropertyEditorSupport (java.beans.PropertyEditorSupport)23 PropertyValue (org.springframework.beans.PropertyValue)16 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)16 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)16 NestedTestBean (org.springframework.tests.sample.beans.NestedTestBean)15 ScannedGenericBeanDefinition (org.springframework.context.annotation.ScannedGenericBeanDefinition)14 HashMap (java.util.HashMap)13 BeanWrapper (org.springframework.beans.BeanWrapper)12 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)11 ParseException (java.text.ParseException)9 RelaxedDataBinder (org.springframework.boot.bind.RelaxedDataBinder)9 BooleanTestBean (org.springframework.tests.sample.beans.BooleanTestBean)9