Search in sources :

Example 76 with BeanWrapper

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

the class AbstractAutowireCapableBeanFactory method autowireBean.

@Override
public void autowireBean(Object existingBean) {
    // Use non-singleton bean definition, to avoid registering bean as dependent bean.
    RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
    bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    initBeanWrapper(bw);
    populateBean(bd.getBeanClass().getName(), bd, bw);
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl)

Example 77 with BeanWrapper

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

the class AbstractAutowireCapableBeanFactory method doCreateBean.

/**
	 * 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
	 * @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 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 != null ? instanceWrapper.getWrappedInstance() : null);
    Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    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.isDebugEnabled()) {
            logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, new ObjectFactory<Object>() {

            @Override
            public Object getObject() throws BeansException {
                return getEarlyBeanReference(beanName, mbd, bean);
            }
        });
    }
    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        populateBean(beanName, mbd, instanceWrapper);
        if (exposedObject != null) {
            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;
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) BeanCurrentlyInCreationException(org.springframework.beans.factory.BeanCurrentlyInCreationException) BeanWrapper(org.springframework.beans.BeanWrapper) BeansException(org.springframework.beans.BeansException)

Example 78 with BeanWrapper

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

the class AbstractAutowireCapableBeanFactory method instantiateBean.

/**
	 * Instantiate the given bean using its default constructor.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @return BeanWrapper for the new instance
	 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {
                    return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                }
            }, getAccessControlContext());
        } else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PrivilegedAction(java.security.PrivilegedAction) AutowireCapableBeanFactory(org.springframework.beans.factory.config.AutowireCapableBeanFactory) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory)

Example 79 with BeanWrapper

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

the class AbstractAutowireCapableBeanFactory method getSingletonFactoryBeanForTypeCheck.

//---------------------------------------------------------------------
// Implementation methods
//---------------------------------------------------------------------
/**
	 * 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
	 * @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
	 */
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
    synchronized (getSingletonMutex()) {
        BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
        if (bw != null) {
            return (FactoryBean<?>) bw.getWrappedInstance();
        }
        if (isSingletonCurrentlyInCreation(beanName) || (mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
            return null;
        }
        Object instance = null;
        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;
    }
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) FactoryBean(org.springframework.beans.factory.FactoryBean)

Example 80 with BeanWrapper

use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.

the class BasePolicy method matchAll.

private boolean matchAll(final T iface) {
    final BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(iface);
    for (final Entry<String, String> term : getCriteria().entrySet()) {
        final String val = getPropertyValueAsString(bean, term.getKey());
        final String matchExpression = term.getValue();
        if (!match(val, matchExpression)) {
            return false;
        }
    }
    return true;
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper)

Aggregations

BeanWrapper (org.springframework.beans.BeanWrapper)144 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)79 Test (org.junit.jupiter.api.Test)31 NumberTestBean (org.springframework.beans.testfixture.beans.NumberTestBean)21 BooleanTestBean (org.springframework.beans.testfixture.beans.BooleanTestBean)20 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)19 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)18 IndexedTestBean (org.springframework.beans.testfixture.beans.IndexedTestBean)18 TestBean (org.springframework.beans.testfixture.beans.TestBean)18 Consumes (javax.ws.rs.Consumes)16 PUT (javax.ws.rs.PUT)16 Path (javax.ws.rs.Path)16 PropertyEditorSupport (java.beans.PropertyEditorSupport)14 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)14 HashSet (java.util.HashSet)12 BeansException (org.springframework.beans.BeansException)12 PropertyDescriptor (java.beans.PropertyDescriptor)11 OnmsNode (org.opennms.netmgt.model.OnmsNode)9 Test (org.junit.Test)6 BigDecimal (java.math.BigDecimal)5