Example usage for org.springframework.beans BeanWrapper getWrappedInstance

List of usage examples for org.springframework.beans BeanWrapper getWrappedInstance

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapper getWrappedInstance.

Prototype

Object getWrappedInstance();

Source Link

Document

Return the bean instance wrapped by this object.

Usage

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./* ww w.j a  va 2s .co m*/
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes and the element named after the bean object's
 * class name. For example:
 * <p>
 * 
 * <pre>
 * &lt;PowerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @return the element, as an XML DOM Document
 */
protected Element getElement(BeanWrapper bean, Document dom) {
    String elementName = bean.getWrappedInstance().getClass().getSimpleName();
    return getElement(bean, elementName, dom);
}

From source file:gov.nih.nci.cabig.caaers.web.utils.WebUtils.java

private static Object extractProperty(BeanWrapper wrappedItem, String propertyName) {
    if (wrappedItem.getWrappedInstance() == null) {
        return null;
    } else if (propertyName == null) {
        return wrappedItem.getWrappedInstance().toString();
    } else {/*from  ww  w .  j  a va  2 s.co  m*/
        return wrappedItem.getPropertyValue(propertyName);
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

@SuppressWarnings("unchecked")
private Object autoCreatePropertyIfPossible(BeanWrapper wrapper, String propertyName, Object propertyValue) {

    propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
    int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
    int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
    String propertyNameWithIndex = propertyName;
    if (currentKeyStart > -1) {
        propertyName = propertyName.substring(0, currentKeyStart);
    }//from   ww  w .  j  a va  2  s .co  m

    Class<?> type = wrapper.getPropertyType(propertyName);
    Object val = wrapper.isReadableProperty(propertyName) ? wrapper.getPropertyValue(propertyName) : null;

    LOG.debug(
            "Checking if auto-create is possible for property [" + propertyName + "] and type [" + type + "]");
    if (type != null && val == null && (isDomainClass(type) || isEmbedded(wrapper, propertyName))) {
        if (!shouldPropertyValueSkipAutoCreate(propertyValue)
                && isNullAndWritableProperty(wrapper, propertyName)) {
            if (isDomainClass(type)) {
                Object created = autoInstantiateDomainInstance(type);
                if (created != null) {
                    val = created;
                    wrapper.setPropertyValue(propertyName, created);
                }
            } else if (isEmbedded(wrapper, propertyName)) {
                Object created = autoInstantiateEmbeddedInstance(type);
                if (created != null) {
                    val = created;
                    wrapper.setPropertyValue(propertyName, created);
                }
            }
        }
    } else {
        final Object beanInstance = wrapper.getWrappedInstance();
        if (type != null && Collection.class.isAssignableFrom(type)) {
            Collection<?> c = null;
            final Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);

            if (isNullAndWritableProperty(wrapper, propertyName)) {
                c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type),
                        referencedType);
            } else {
                if (wrapper.isReadableProperty(propertyName)) {
                    c = decorateCollectionForDomainAssociation(
                            (Collection<?>) wrapper.getPropertyValue(propertyName), referencedType);
                }
            }

            if (wrapper.isWritableProperty(propertyName) && c != null) {
                wrapper.setPropertyValue(propertyName, c);
            }

            val = c;

            if (c != null && currentKeyStart > -1 && currentKeyEnd > -1) {
                String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
                int index = Integer.parseInt(indexString);

                // See if we have an instance in the collection. If so, that specific instance
                // is the value to return for this indexed property.
                Object instance = findIndexedValue(c, index);
                if (instance != null) {
                    val = instance;
                }
                // If no value in the collection, this might be a domain class
                else if (isDomainClass(referencedType)) {
                    instance = autoInstantiateDomainInstance(referencedType);
                    if (instance != null) {
                        val = instance;
                        if (index == c.size()) {
                            addAssociationToTarget(propertyName, beanInstance, instance);
                        } else if (index > c.size()) {
                            while (index > c.size()) {
                                addAssociationToTarget(propertyName, beanInstance,
                                        autoInstantiateDomainInstance(referencedType));
                            }

                            addAssociationToTarget(propertyName, beanInstance, instance);
                        }
                    }
                }
            }
        } else if (type != null && Map.class.isAssignableFrom(type)) {
            Map<String, Object> map;
            if (isNullAndWritableProperty(wrapper, propertyName)) {
                map = new HashMap<String, Object>();
                wrapper.setPropertyValue(propertyName, map);
            } else {
                map = (Map) wrapper.getPropertyValue(propertyName);
            }
            val = map;
            wrapper.setPropertyValue(propertyName, val);

            if (currentKeyStart > -1 && currentKeyEnd > -1) {
                String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
                Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
                if (isDomainClass(referencedType)) {
                    final Object domainInstance = autoInstantiateDomainInstance(referencedType);
                    val = domainInstance;
                    map.put(indexString, domainInstance);
                }
            }
        }
    }

    return val;
}

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

/**
 * Actually create the specified bean. Pre-creation processing has already happened
 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
 * <p>Differentiates between default bean instantiation, use of a
 * factory method, and autowiring a constructor.
 * @param beanName the name of the bean/* w ww .j a v a2 s  . c o  m*/
 * @param mbd the merged bean definition for the bean
 * @param args explicit arguments to use for constructor or factory method invocation
 * @return a new instance of the bean
 * @throws BeanCreationException if the bean could not be created
 * @see #instantiateBean
 * @see #instantiateUsingFactoryMethod
 * @see #autowireConstructor
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd,
        final @Nullable Object[] args) throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            } catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences
            && isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName
                    + "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    } catch (Throwable ex) {
        if (ex instanceof BeanCreationException
                && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        } else {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Initialization of bean failed", ex);
        }
    }

    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName
                            + "' has been injected into other beans ["
                            + StringUtils.collectionToCommaDelimitedString(actualDependentBeans)
                            + "] in its raw version as part of a circular reference, but has eventually been "
                            + "wrapped. This means that said other beans do not use the final version of the "
                            + "bean. This is often the result of over-eager type matching - consider using "
                            + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    } catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature",
                ex);
    }

    return exposedObject;
}

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

/**
 * Obtain a "shortcut" singleton FactoryBean instance to use for a
 * {@code getObjectType()} call, without full initialization of the FactoryBean.
 * @param beanName the name of the bean//from w  w w .j a va 2 s .  co m
 * @param mbd the bean definition for the bean
 * @return the FactoryBean instance, or {@code null} to indicate
 * that we couldn't obtain a shortcut FactoryBean instance
 */
@Nullable
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
    synchronized (getSingletonMutex()) {
        BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
        if (bw != null) {
            return (FactoryBean<?>) bw.getWrappedInstance();
        }
        Object beanInstance = getSingleton(beanName, false);
        if (beanInstance instanceof FactoryBean) {
            return (FactoryBean<?>) beanInstance;
        }
        if (isSingletonCurrentlyInCreation(beanName) || (mbd.getFactoryBeanName() != null
                && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
            return null;
        }

        Object instance;
        try {
            // Mark this bean as currently in creation, even if just partially.
            beforeSingletonCreation(beanName);
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            instance = resolveBeforeInstantiation(beanName, mbd);
            if (instance == null) {
                bw = createBeanInstance(beanName, mbd, null);
                instance = bw.getWrappedInstance();
            }
        } finally {
            // Finished partial creation of this bean.
            afterSingletonCreation(beanName);
        }

        FactoryBean<?> fb = getFactoryBean(beanName, instance);
        if (bw != null) {
            this.factoryBeanInstanceCache.put(beanName, bw);
        }
        return fb;
    }
}

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

/**
 * Obtain a "shortcut" non-singleton FactoryBean instance to use for a
 * {@code getObjectType()} call, without full initialization of the FactoryBean.
 * @param beanName the name of the bean// ww w .  j  av a  2s . c om
 * @param mbd the bean definition for the bean
 * @return the FactoryBean instance, or {@code null} to indicate
 * that we couldn't obtain a shortcut FactoryBean instance
 */
@Nullable
private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
    if (isPrototypeCurrentlyInCreation(beanName)) {
        return null;
    }

    Object instance = null;
    try {
        // Mark this bean as currently in creation, even if just partially.
        beforePrototypeCreation(beanName);
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        instance = resolveBeforeInstantiation(beanName, mbd);
        if (instance == null) {
            BeanWrapper bw = createBeanInstance(beanName, mbd, null);
            instance = bw.getWrappedInstance();
        }
    } catch (BeanCreationException ex) {
        // Can only happen when getting a FactoryBean.
        if (logger.isDebugEnabled()) {
            logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex);
        }
        onSuppressedException(ex);
        return null;
    } finally {
        // Finished partial creation of this bean.
        afterPrototypeCreation(beanName);
    }

    return getFactoryBean(beanName, instance);
}

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

/**
 * Populate the bean instance in the given BeanWrapper with the property values
 * from the bean definition./*from  w  ww  . j a  va  2  s.co m*/
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @param bw the BeanWrapper with bean instance
 */
@SuppressWarnings("deprecation") // for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    if (bw == null) {
        if (mbd.hasPropertyValues()) {
            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;
    }

    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    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);

    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    if (filteredPds == null) {
                        filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(),
                            beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

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

/**
 * Abstract method defining "autowire by type" (bean properties by type) behavior.
 * <p>This is like PicoContainer default, in which there must be exactly one bean
 * of the property type in the bean factory. This makes bean factories simple to
 * configure for small namespaces, but doesn't work as well as standard Spring
 * behavior for bigger applications./* w  ww .j a v  a 2 s . co m*/
 * @param beanName the name of the bean to autowire by type
 * @param mbd the merged bean definition to update through autowiring
 * @param bw the BeanWrapper from which we can obtain information about the bean
 * @param pvs the PropertyValues to register wired objects with
 */
protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw,
        MutablePropertyValues pvs) {

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }

    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // Don't try autowiring by type for type Object: never makes sense,
            // even if it technically is a unsatisfied, non-simple property.
            if (Object.class != pd.getPropertyType()) {
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Autowiring by type from bean name '" + beanName + "' via property '"
                                + propertyName + "' to bean named '" + autowiredBeanName + "'");
                    }
                }
                autowiredBeanNames.clear();
            }
        } catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
        }
    }
}

From source file:org.springframework.faces.mvc.bind.ReverseDataBinder.java

/**
 * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will
 * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues}
 * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using
 * the property editors bound to the original dataBinder.
 * @return property values that could be re-bound using the data binder
 * @throws IllegalStateException if the target object values cannot be bound
 *//*from w  ww. j  av a 2s .  c  om*/
public PropertyValues reverseBind() {
    Assert.notNull(dataBinder.getTarget(),
            "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object");
    MutablePropertyValues rtn = new MutablePropertyValues();
    BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(dataBinder.getTarget());
    PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors();

    BeanWrapper defaultValues = null;
    if (skipDefaultValues) {
        defaultValues = newDefaultTargetValues(dataBinder.getTarget());
    }

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor property = propertyDescriptors[i];
        String propertyName = getPropertyName(property);
        Object propertyValue = target.getPropertyValue(propertyName);

        if (isSkippedProperty(property)) {
            continue;
        }

        if (!isMutableProperty(property)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods");
            }
            continue;
        }

        if (defaultValues != null
                && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Skipping '" + propertyName + "' as property contains default value");
            }
            continue;
        }

        // Find a property editor
        PropertyEditorRegistrySupport propertyEditorRegistrySupport = null;
        if (target instanceof PropertyEditorRegistrySupport) {
            propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target;
        }
        PropertyEditor propertyEditor = findEditor(propertyEditorRegistrySupport, target.getWrappedInstance(),
                target.getPropertyType(propertyName), property);

        // Convert and store the value
        String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor);
        if (convertedPropertyValue != null) {
            rtn.addPropertyValue(propertyName, convertedPropertyValue);
        }
    }

    dataBinder.bind(rtn);
    BindingResult bindingResult = dataBinder.getBindingResult();
    if (bindingResult.hasErrors()) {
        throw new IllegalStateException("Unable to reverse bind from target '" + dataBinder.getObjectName()
                + "', the properties '" + rtn + "' will result in binding errors when re-bound "
                + bindingResult.getAllErrors());
    }
    return rtn;
}