Search in sources :

Example 26 with PropertyValue

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

the class RelaxedDataBinder method modifyProperties.

/**
	 * Modify the property values so that period separated property paths are valid for
	 * map keys. Also creates new maps for properties of map type that are null (assuming
	 * all maps are potentially nested). The standard bracket {@code[...]} dereferencing
	 * is also accepted.
	 * @param propertyValues the property values
	 * @param target the target object
	 * @return modified property values
	 */
private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, Object target) {
    propertyValues = getPropertyValuesForNamePrefix(propertyValues);
    if (target instanceof MapHolder) {
        propertyValues = addMapPrefix(propertyValues);
    }
    BeanWrapper wrapper = new BeanWrapperImpl(target);
    wrapper.setConversionService(new RelaxedConversionService(getConversionService()));
    wrapper.setAutoGrowNestedPaths(true);
    List<PropertyValue> sortedValues = new ArrayList<>();
    Set<String> modifiedNames = new HashSet<>();
    List<String> sortedNames = getSortedPropertyNames(propertyValues);
    for (String name : sortedNames) {
        PropertyValue propertyValue = propertyValues.getPropertyValue(name);
        PropertyValue modifiedProperty = modifyProperty(wrapper, propertyValue);
        if (modifiedNames.add(modifiedProperty.getName())) {
            sortedValues.add(modifiedProperty);
        }
    }
    return new MutablePropertyValues(sortedValues);
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) ArrayList(java.util.ArrayList) PropertyValue(org.springframework.beans.PropertyValue) HashSet(java.util.HashSet)

Example 27 with PropertyValue

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

the class DefaultListableBeanFactoryTests method doTestFieldSettingWithInstantiationAwarePostProcessor.

private void doTestFieldSettingWithInstantiationAwarePostProcessor(final boolean skipPropertyPopulation) {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
    int ageSetByPropertyValue = 27;
    bd.getPropertyValues().addPropertyValue(new PropertyValue("age", new Integer(ageSetByPropertyValue)));
    lbf.registerBeanDefinition("test", bd);
    final String nameSetOnField = "nameSetOnField";
    lbf.addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() {

        @Override
        public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
            TestBean tb = (TestBean) bean;
            try {
                Field f = TestBean.class.getDeclaredField("name");
                f.setAccessible(true);
                f.set(tb, nameSetOnField);
                return !skipPropertyPopulation;
            } catch (Exception ex) {
                fail("Unexpected exception: " + ex);
                // Keep compiler happy about return
                throw new IllegalStateException();
            }
        }
    });
    lbf.preInstantiateSingletons();
    TestBean tb = (TestBean) lbf.getBean("test");
    assertEquals("Name was set on field by IAPP", nameSetOnField, tb.getName());
    if (!skipPropertyPopulation) {
        assertEquals("Property value still set", ageSetByPropertyValue, tb.getAge());
    } else {
        assertEquals("Property value was NOT set and still has default value", 0, tb.getAge());
    }
}
Also used : InstantiationAwareBeanPostProcessorAdapter(org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) PropertyValue(org.springframework.beans.PropertyValue) ParseException(java.text.ParseException) TypeMismatchException(org.springframework.beans.TypeMismatchException) NotWritablePropertyException(org.springframework.beans.NotWritablePropertyException) ExpectedException(org.junit.rules.ExpectedException) MalformedURLException(java.net.MalformedURLException) BeansException(org.springframework.beans.BeansException) Field(java.lang.reflect.Field) ITestBean(org.springframework.tests.sample.beans.ITestBean) DerivedTestBean(org.springframework.tests.sample.beans.DerivedTestBean) TestBean(org.springframework.tests.sample.beans.TestBean) NestedTestBean(org.springframework.tests.sample.beans.NestedTestBean) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeansException(org.springframework.beans.BeansException)

Example 28 with PropertyValue

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

the class BeanComponentDefinition method findInnerBeanDefinitionsAndBeanReferences.

private void findInnerBeanDefinitionsAndBeanReferences(BeanDefinition beanDefinition) {
    List<BeanDefinition> innerBeans = new ArrayList<>();
    List<BeanReference> references = new ArrayList<>();
    PropertyValues propertyValues = beanDefinition.getPropertyValues();
    for (int i = 0; i < propertyValues.getPropertyValues().length; i++) {
        PropertyValue propertyValue = propertyValues.getPropertyValues()[i];
        Object value = propertyValue.getValue();
        if (value instanceof BeanDefinitionHolder) {
            innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());
        } else if (value instanceof BeanDefinition) {
            innerBeans.add((BeanDefinition) value);
        } else if (value instanceof BeanReference) {
            references.add((BeanReference) value);
        }
    }
    this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[innerBeans.size()]);
    this.beanReferences = references.toArray(new BeanReference[references.size()]);
}
Also used : PropertyValues(org.springframework.beans.PropertyValues) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) ArrayList(java.util.ArrayList) PropertyValue(org.springframework.beans.PropertyValue) BeanReference(org.springframework.beans.factory.config.BeanReference) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition)

Example 29 with PropertyValue

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

the class AbstractAutowireCapableBeanFactory method applyPropertyValues.

/**
	 * Apply the given property values, resolving any runtime references
	 * to other beans in this bean factory. Must use deep copy, so we
	 * don't permanently modify this property.
	 * @param beanName the bean name passed for better exception information
	 * @param mbd the merged bean definition
	 * @param bw the BeanWrapper wrapping the target object
	 * @param pvs the new property values
	 */
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs == null || pvs.isEmpty()) {
        return;
    }
    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;
    if (System.getSecurityManager() != null) {
        if (bw instanceof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
    }
    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                bw.setPropertyValues(mpvs);
                return;
            } catch (BeansException ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    } else {
        original = Arrays.asList(pvs.getPropertyValues());
    }
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    // Create a deep copy, resolving any references for values.
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            deepCopy.add(pv);
        } else {
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // in order to avoid re-conversion for every created bean instance.
            if (resolvedValue == originalValue) {
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            } else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            } else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }
    // Set our (possibly massaged) deep copy.
    try {
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    } catch (BeansException ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) ArrayList(java.util.ArrayList) PropertyValue(org.springframework.beans.PropertyValue) TypeConverter(org.springframework.beans.TypeConverter) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) Collection(java.util.Collection) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) BeansException(org.springframework.beans.BeansException)

Example 30 with PropertyValue

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

the class BeanDefinitionParserDelegate method parsePropertyElement.

/**
	 * Parse a property element.
	 */
public void parsePropertyElement(Element ele, BeanDefinition bd) {
    String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
    if (!StringUtils.hasLength(propertyName)) {
        error("Tag 'property' must have a 'name' attribute", ele);
        return;
    }
    this.parseState.push(new PropertyEntry(propertyName));
    try {
        if (bd.getPropertyValues().contains(propertyName)) {
            error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
            return;
        }
        Object val = parsePropertyValue(ele, bd, propertyName);
        PropertyValue pv = new PropertyValue(propertyName, val);
        parseMetaElements(ele, pv);
        pv.setSource(extractSource(ele));
        bd.getPropertyValues().addPropertyValue(pv);
    } finally {
        this.parseState.pop();
    }
}
Also used : PropertyEntry(org.springframework.beans.factory.parsing.PropertyEntry) PropertyValue(org.springframework.beans.PropertyValue)

Aggregations

PropertyValue (org.springframework.beans.PropertyValue)41 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)16 Test (org.junit.Test)15 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)8 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)7 FieldAccessBean (org.springframework.tests.sample.beans.FieldAccessBean)6 ArrayList (java.util.ArrayList)5 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)5 ITestBean (org.springframework.tests.sample.beans.ITestBean)5 TestBean (org.springframework.tests.sample.beans.TestBean)5 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)4 BeanWrapper (org.springframework.beans.BeanWrapper)3 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)3 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)3 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)3 BigInteger (java.math.BigInteger)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 BeansException (org.springframework.beans.BeansException)2