Search in sources :

Example 1 with SmartFactoryBean

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

the class DefaultListableBeanFactory method preInstantiateSingletons.

@Override
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }
    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            if (isFactoryBean(beanName)) {
                final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                boolean isEagerInit;
                if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                    isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                        @Override
                        public Boolean run() {
                            return ((SmartFactoryBean<?>) factory).isEagerInit();
                        }
                    }, getAccessControlContext());
                } else {
                    isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit());
                }
                if (isEagerInit) {
                    getBean(beanName);
                }
            } else {
                getBean(beanName);
            }
        }
    }
    // Trigger post-initialization callback for all applicable beans...
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {

                    @Override
                    public Object run() {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }
                }, getAccessControlContext());
            } else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean) SmartInitializingSingleton(org.springframework.beans.factory.SmartInitializingSingleton) PrivilegedAction(java.security.PrivilegedAction) FactoryBean(org.springframework.beans.factory.FactoryBean) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean)

Example 2 with SmartFactoryBean

use of org.springframework.beans.factory.SmartFactoryBean in project mule by mulesoft.

the class DefaultListableBeanFactory method preInstantiateSingletons.

@Override
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }
    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            if (isFactoryBean(beanName)) {
                final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                boolean isEagerInit;
                if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                    isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                        @Override
                        public Boolean run() {
                            return ((SmartFactoryBean<?>) factory).isEagerInit();
                        }
                    }, getAccessControlContext());
                } else {
                    isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit());
                }
                if (isEagerInit) {
                    getBean(beanName);
                }
            } else {
                getBean(beanName);
            }
        }
    }
    // Trigger post-initialization callback for all applicable beans...
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {

                    @Override
                    public Object run() {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }
                }, getAccessControlContext());
            } else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean) SmartInitializingSingleton(org.springframework.beans.factory.SmartInitializingSingleton) PrivilegedAction(java.security.PrivilegedAction) FactoryBean(org.springframework.beans.factory.FactoryBean) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean)

Example 3 with SmartFactoryBean

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

the class AbstractBeanFactory method isPrototype.

@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
    String beanName = transformedBeanName(name);
    BeanFactory parentBeanFactory = getParentBeanFactory();
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
        // No bean definition found in this factory -> delegate to parent.
        return parentBeanFactory.isPrototype(originalBeanName(name));
    }
    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    if (mbd.isPrototype()) {
        // In case of FactoryBean, return singleton status of created object if not a dereference.
        return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
    }
    // However, FactoryBean may still produce a prototype object...
    if (BeanFactoryUtils.isFactoryDereference(name)) {
        return false;
    }
    if (isFactoryBean(beanName, mbd)) {
        final FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                @Override
                public Boolean run() {
                    return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton());
                }
            }, getAccessControlContext());
        } else {
            return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton());
        }
    } else {
        return false;
    }
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean) FactoryBean(org.springframework.beans.factory.FactoryBean) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean)

Example 4 with SmartFactoryBean

use of org.springframework.beans.factory.SmartFactoryBean in project mule by mulesoft.

the class ObjectFactoryClassRepository method getObjectFactoryDynamicClass.

private Class<ObjectFactory> getObjectFactoryDynamicClass(final ComponentBuildingDefinition componentBuildingDefinition, final Class objectFactoryType, final Class createdObjectType, final Supplier<Boolean> isLazyInitFunction, final Optional<Consumer<Object>> instancePostCreationFunction) {
    /*
     * We need this to allow spring create the object using a FactoryBean but using the object factory setters and getters so we
     * create as FactoryBean a dynamic class that will have the same attributes and methods as the ObjectFactory that the user
     * defined. This way our API does not expose spring specific classes.
     */
    Enhancer enhancer = new Enhancer();
    // Use SmartFactoryBean since it's the only way to force spring to pre-instantiate FactoryBean for singletons
    enhancer.setInterfaces(new Class[] { SmartFactoryBean.class });
    enhancer.setSuperclass(objectFactoryType);
    enhancer.setCallbackType(MethodInterceptor.class);
    if (SmartFactoryBean.class.getClassLoader() != objectFactoryType.getClassLoader()) {
        // CGLIB needs access to both the spring interface and the extended factory class.
        // If the factory class is defined in a plugin, its classloader has to be passed.
        enhancer.setClassLoader(new CompositeClassLoader(ObjectFactoryClassRepository.class.getClassLoader(), objectFactoryType.getClassLoader()));
    }
    // The use of the CGLIB cache is turned off when a post creation function is passed as argument in order to
    // enrich the created proxy with properties. This is only to enable injecting properties in components
    // from the compatibility module.
    // Setting this to false will generate an excessive amount of different proxy classes loaded by the container CL
    // that will end up in Metaspace OOM.
    enhancer.setUseCache(!instancePostCreationFunction.isPresent());
    Class<ObjectFactory> factoryBeanClass = enhancer.createClass();
    registerStaticCallbacks(factoryBeanClass, new Callback[] { (MethodInterceptor) (obj, method, args, proxy) -> {
        final boolean eager = !isLazyInitFunction.get();
        if (method.getName().equals("isSingleton")) {
            return !componentBuildingDefinition.isPrototype();
        }
        if (method.getName().equals("getObjectType") && !ObjectTypeProvider.class.isAssignableFrom(obj.getClass())) {
            return createdObjectType;
        }
        if (method.getName().equals("getObject")) {
            Object createdInstance = proxy.invokeSuper(obj, args);
            instancePostCreationFunction.ifPresent(consumer -> consumer.accept(createdInstance));
            return createdInstance;
        }
        if (method.getName().equals("isPrototype")) {
            return componentBuildingDefinition.isPrototype();
        }
        if (method.getName().equals("isEagerInit")) {
            return eager;
        }
        return proxy.invokeSuper(obj, args);
    } });
    return factoryBeanClass;
}
Also used : MethodInterceptor(org.springframework.cglib.proxy.MethodInterceptor) Consumer(java.util.function.Consumer) Enhancer(org.springframework.cglib.proxy.Enhancer) ComponentBuildingDefinition(org.mule.runtime.dsl.api.component.ComponentBuildingDefinition) Enhancer.registerStaticCallbacks(org.springframework.cglib.proxy.Enhancer.registerStaticCallbacks) CompositeClassLoader(org.mule.runtime.core.internal.util.CompositeClassLoader) Callback(org.springframework.cglib.proxy.Callback) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean) Optional(java.util.Optional) ObjectFactory(org.mule.runtime.dsl.api.component.ObjectFactory) Supplier(java.util.function.Supplier) ObjectTypeProvider(org.mule.runtime.dsl.api.component.ObjectTypeProvider) ObjectTypeProvider(org.mule.runtime.dsl.api.component.ObjectTypeProvider) Enhancer(org.springframework.cglib.proxy.Enhancer) ObjectFactory(org.mule.runtime.dsl.api.component.ObjectFactory) SmartFactoryBean(org.springframework.beans.factory.SmartFactoryBean) CompositeClassLoader(org.mule.runtime.core.internal.util.CompositeClassLoader)

Aggregations

SmartFactoryBean (org.springframework.beans.factory.SmartFactoryBean)4 FactoryBean (org.springframework.beans.factory.FactoryBean)3 PrivilegedAction (java.security.PrivilegedAction)2 ArrayList (java.util.ArrayList)2 SmartInitializingSingleton (org.springframework.beans.factory.SmartInitializingSingleton)2 Optional (java.util.Optional)1 Consumer (java.util.function.Consumer)1 Supplier (java.util.function.Supplier)1 CompositeClassLoader (org.mule.runtime.core.internal.util.CompositeClassLoader)1 ComponentBuildingDefinition (org.mule.runtime.dsl.api.component.ComponentBuildingDefinition)1 ObjectFactory (org.mule.runtime.dsl.api.component.ObjectFactory)1 ObjectTypeProvider (org.mule.runtime.dsl.api.component.ObjectTypeProvider)1 BeanFactory (org.springframework.beans.factory.BeanFactory)1 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)1 Callback (org.springframework.cglib.proxy.Callback)1 Enhancer (org.springframework.cglib.proxy.Enhancer)1 Enhancer.registerStaticCallbacks (org.springframework.cglib.proxy.Enhancer.registerStaticCallbacks)1 MethodInterceptor (org.springframework.cglib.proxy.MethodInterceptor)1