Search in sources :

Example 1 with Scope

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

the class AbstractBeanFactory method registerDisposableBeanIfNecessary.

/**
	 * Add the given bean to the list of disposable beans in this factory,
	 * registering its DisposableBean interface and/or the given destroy method
	 * to be called on factory shutdown (if applicable). Only applies to singletons.
	 * @param beanName the name of the bean
	 * @param bean the bean instance
	 * @param mbd the bean definition for the bean
	 * @see RootBeanDefinition#isSingleton
	 * @see RootBeanDefinition#getDependsOn
	 * @see #registerDisposableBean
	 * @see #registerDependentBean
	 */
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            // Register a DisposableBean implementation that performs all destruction
            // work for the given bean: DestructionAwareBeanPostProcessors,
            // DisposableBean interface, custom destroy method.
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        } else {
            // A bean with a custom scope...
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
            scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
    }
}
Also used : AccessControlContext(java.security.AccessControlContext) Scope(org.springframework.beans.factory.config.Scope)

Example 2 with Scope

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

the class AbstractBeanFactory method doGetBean.

/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * @param name the name of the bean to retrieve
	 * @param requiredType the required type of the bean to retrieve
	 * @param args arguments to use when creating a bean instance using explicit arguments
	 * (only applied when creating a new instance as opposed to retrieving an existing one)
	 * @param typeCheckOnly whether the instance is obtained for a type check,
	 * not for actual use
	 * @return an instance of the bean
	 * @throws BeansException if the bean could not be created
	 */
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
    final String beanName = transformedBeanName(name);
    Object bean;
    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isDebugEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
            } else {
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    } else {
        // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            } else {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }
        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }
        try {
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            // Guarantee initialization of beans that the current bean depends on.
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    registerDependentBean(dep, beanName);
                    getBean(dep);
                }
            }
            // Create bean instance.
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {

                    @Override
                    public Object getObject() throws BeansException {
                        try {
                            return createBean(beanName, mbd, args);
                        } catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            } else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                } finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {

                        @Override
                        public Object getObject() throws BeansException {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            } finally {
                                afterPrototypeCreation(beanName);
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                } catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex);
                }
            }
        } catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }
    // Check if required type matches the type of the actual bean instance.
    if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
        try {
            return getTypeConverter().convertIfNecessary(bean, requiredType);
        } catch (TypeMismatchException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) TypeMismatchException(org.springframework.beans.TypeMismatchException) BeanCurrentlyInCreationException(org.springframework.beans.factory.BeanCurrentlyInCreationException) BeanNotOfRequiredTypeException(org.springframework.beans.factory.BeanNotOfRequiredTypeException) ObjectFactory(org.springframework.beans.factory.ObjectFactory) Scope(org.springframework.beans.factory.config.Scope) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) BeansException(org.springframework.beans.BeansException)

Example 3 with Scope

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

the class AbstractBeanFactory method registerScope.

@Override
public void registerScope(String scopeName, Scope scope) {
    Assert.notNull(scopeName, "Scope identifier must not be null");
    Assert.notNull(scope, "Scope must not be null");
    if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
        throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
    }
    Scope previous = this.scopes.put(scopeName, scope);
    if (previous != null && previous != scope) {
        if (logger.isInfoEnabled()) {
            logger.info("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
        }
    }
}
Also used : Scope(org.springframework.beans.factory.config.Scope)

Example 4 with Scope

use of org.springframework.beans.factory.config.Scope in project pentaho-platform by pentaho.

the class StandaloneSpringPentahoObjectFactory method init.

/**
 * Initializes this object factory by creating a self-contained Spring {@link ApplicationContext} if one is not passed
 * in.
 *
 * @param configFile the Spring bean definition XML file
 * @param context    the {@link ApplicationContext} object, if null, then this method will create one
 */
public void init(String configFile, Object context) {
    if (context == null) {
        // beanFactory = new FileSystemXmlApplicationContext(configFile);
        FileSystemXmlApplicationContext appCtx = new FileSystemXmlApplicationContext(configFile);
        appCtx.refresh();
        appCtx.addBeanFactoryPostProcessor(new PentahoBeanScopeValidatorPostProcessor());
        Scope requestScope = new ThreadLocalScope();
        appCtx.getBeanFactory().registerScope("request", requestScope);
        Scope sessionScope = new ThreadLocalScope();
        appCtx.getBeanFactory().registerScope("session", sessionScope);
        beanFactory = appCtx;
    } else {
        if (!(context instanceof ConfigurableApplicationContext)) {
            String msg = Messages.getInstance().getErrorString(// $NON-NLS-1$
            "StandalonePentahoObjectFactory.ERROR_0001_CONTEXT_NOT_SUPPORTED", getClass().getSimpleName(), "GenericApplicationContext", // $NON-NLS-1$
            context.getClass().getName());
            throw new IllegalArgumentException(msg);
        }
        ConfigurableApplicationContext configAppCtx = (ConfigurableApplicationContext) context;
        if (configAppCtx.getBeanFactory().getRegisteredScope("request") == null) {
            Scope requestScope = new ThreadLocalScope();
            configAppCtx.getBeanFactory().registerScope("request", requestScope);
        }
        if (configAppCtx.getBeanFactory().getRegisteredScope("session") == null) {
            Scope sessionScope = new ThreadLocalScope();
            configAppCtx.getBeanFactory().registerScope("session", sessionScope);
        }
        setBeanFactory(configAppCtx);
    }
}
Also used : FileSystemXmlApplicationContext(org.springframework.context.support.FileSystemXmlApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Scope(org.springframework.beans.factory.config.Scope) PentahoBeanScopeValidatorPostProcessor(org.pentaho.platform.engine.core.system.objfac.spring.PentahoBeanScopeValidatorPostProcessor)

Example 5 with Scope

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

the class ApplicationContextExpressionTests method genericApplicationContext.

@Test
@SuppressWarnings("deprecation")
void genericApplicationContext() throws Exception {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
    ac.getBeanFactory().registerScope("myScope", new Scope() {

        @Override
        public Object get(String name, ObjectFactory<?> objectFactory) {
            return objectFactory.getObject();
        }

        @Override
        public Object remove(String name) {
            return null;
        }

        @Override
        public void registerDestructionCallback(String name, Runnable callback) {
        }

        @Override
        public Object resolveContextualObject(String key) {
            if (key.equals("mySpecialAttr")) {
                return "42";
            } else {
                return null;
            }
        }

        @Override
        public String getConversationId() {
            return null;
        }
    });
    ac.getBeanFactory().setConversionService(new DefaultConversionService());
    org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ppc = new org.springframework.beans.factory.config.PropertyPlaceholderConfigurer();
    Properties placeholders = new Properties();
    placeholders.setProperty("code", "123");
    ppc.setProperties(placeholders);
    ac.addBeanFactoryPostProcessor(ppc);
    GenericBeanDefinition bd0 = new GenericBeanDefinition();
    bd0.setBeanClass(TestBean.class);
    bd0.getPropertyValues().add("name", "myName");
    bd0.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "original"));
    ac.registerBeanDefinition("tb0", bd0);
    GenericBeanDefinition bd1 = new GenericBeanDefinition();
    bd1.setBeanClassName("#{tb0.class}");
    bd1.setScope("myScope");
    bd1.getConstructorArgumentValues().addGenericArgumentValue("XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ");
    bd1.getConstructorArgumentValues().addGenericArgumentValue("#{mySpecialAttr}");
    ac.registerBeanDefinition("tb1", bd1);
    GenericBeanDefinition bd2 = new GenericBeanDefinition();
    bd2.setBeanClassName("#{tb1.class.name}");
    bd2.setScope("myScope");
    bd2.getPropertyValues().add("name", "{ XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ }");
    bd2.getPropertyValues().add("age", "#{mySpecialAttr}");
    bd2.getPropertyValues().add("country", "${code} #{systemProperties.country}");
    ac.registerBeanDefinition("tb2", bd2);
    GenericBeanDefinition bd3 = new GenericBeanDefinition();
    bd3.setBeanClass(ValueTestBean.class);
    bd3.setScope("myScope");
    ac.registerBeanDefinition("tb3", bd3);
    GenericBeanDefinition bd4 = new GenericBeanDefinition();
    bd4.setBeanClass(ConstructorValueTestBean.class);
    bd4.setScope("myScope");
    ac.registerBeanDefinition("tb4", bd4);
    GenericBeanDefinition bd5 = new GenericBeanDefinition();
    bd5.setBeanClass(MethodValueTestBean.class);
    bd5.setScope("myScope");
    ac.registerBeanDefinition("tb5", bd5);
    GenericBeanDefinition bd6 = new GenericBeanDefinition();
    bd6.setBeanClass(PropertyValueTestBean.class);
    bd6.setScope("myScope");
    ac.registerBeanDefinition("tb6", bd6);
    System.getProperties().put("country", "UK");
    try {
        ac.refresh();
        TestBean tb0 = ac.getBean("tb0", TestBean.class);
        TestBean tb1 = ac.getBean("tb1", TestBean.class);
        assertThat(tb1.getName()).isEqualTo("XXXmyNameYYY42ZZZ");
        assertThat(tb1.getAge()).isEqualTo(42);
        TestBean tb2 = ac.getBean("tb2", TestBean.class);
        assertThat(tb2.getName()).isEqualTo("{ XXXmyNameYYY42ZZZ }");
        assertThat(tb2.getAge()).isEqualTo(42);
        assertThat(tb2.getCountry()).isEqualTo("123 UK");
        ValueTestBean tb3 = ac.getBean("tb3", ValueTestBean.class);
        assertThat(tb3.name).isEqualTo("XXXmyNameYYY42ZZZ");
        assertThat(tb3.age).isEqualTo(42);
        assertThat(tb3.ageFactory.getObject().intValue()).isEqualTo(42);
        assertThat(tb3.country).isEqualTo("123 UK");
        assertThat(tb3.countryFactory.getObject()).isEqualTo("123 UK");
        System.getProperties().put("country", "US");
        assertThat(tb3.country).isEqualTo("123 UK");
        assertThat(tb3.countryFactory.getObject()).isEqualTo("123 US");
        System.getProperties().put("country", "UK");
        assertThat(tb3.country).isEqualTo("123 UK");
        assertThat(tb3.countryFactory.getObject()).isEqualTo("123 UK");
        assertThat(tb3.optionalValue1.get()).isEqualTo("123");
        assertThat(tb3.optionalValue2.get()).isEqualTo("123");
        assertThat(tb3.optionalValue3.isPresent()).isFalse();
        assertThat(tb3.tb).isSameAs(tb0);
        tb3 = SerializationTestUtils.serializeAndDeserialize(tb3);
        assertThat(tb3.countryFactory.getObject()).isEqualTo("123 UK");
        ConstructorValueTestBean tb4 = ac.getBean("tb4", ConstructorValueTestBean.class);
        assertThat(tb4.name).isEqualTo("XXXmyNameYYY42ZZZ");
        assertThat(tb4.age).isEqualTo(42);
        assertThat(tb4.country).isEqualTo("123 UK");
        assertThat(tb4.tb).isSameAs(tb0);
        MethodValueTestBean tb5 = ac.getBean("tb5", MethodValueTestBean.class);
        assertThat(tb5.name).isEqualTo("XXXmyNameYYY42ZZZ");
        assertThat(tb5.age).isEqualTo(42);
        assertThat(tb5.country).isEqualTo("123 UK");
        assertThat(tb5.tb).isSameAs(tb0);
        PropertyValueTestBean tb6 = ac.getBean("tb6", PropertyValueTestBean.class);
        assertThat(tb6.name).isEqualTo("XXXmyNameYYY42ZZZ");
        assertThat(tb6.age).isEqualTo(42);
        assertThat(tb6.country).isEqualTo("123 UK");
        assertThat(tb6.tb).isSameAs(tb0);
    } finally {
        System.getProperties().remove("country");
    }
}
Also used : DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) Properties(java.util.Properties) AutowireCandidateQualifier(org.springframework.beans.factory.support.AutowireCandidateQualifier) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) Scope(org.springframework.beans.factory.config.Scope) TestBean(org.springframework.beans.testfixture.beans.TestBean) AutowireCandidateQualifier(org.springframework.beans.factory.support.AutowireCandidateQualifier) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Test(org.junit.jupiter.api.Test)

Aggregations

Scope (org.springframework.beans.factory.config.Scope)13 Test (org.junit.Test)6 ObjectFactory (org.springframework.beans.factory.ObjectFactory)3 Test (org.junit.jupiter.api.Test)2 AccessControlContext (java.security.AccessControlContext)1 Properties (java.util.Properties)1 PentahoBeanScopeValidatorPostProcessor (org.pentaho.platform.engine.core.system.objfac.spring.PentahoBeanScopeValidatorPostProcessor)1 BeansException (org.springframework.beans.BeansException)1 TypeMismatchException (org.springframework.beans.TypeMismatchException)1 BeanCreationException (org.springframework.beans.factory.BeanCreationException)1 BeanCurrentlyInCreationException (org.springframework.beans.factory.BeanCurrentlyInCreationException)1 BeanFactory (org.springframework.beans.factory.BeanFactory)1 BeanNotOfRequiredTypeException (org.springframework.beans.factory.BeanNotOfRequiredTypeException)1 Qualifier (org.springframework.beans.factory.annotation.Qualifier)1 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)1 ConfigurableListableBeanFactory (org.springframework.beans.factory.config.ConfigurableListableBeanFactory)1 AutowireCandidateQualifier (org.springframework.beans.factory.support.AutowireCandidateQualifier)1 GenericBeanDefinition (org.springframework.beans.factory.support.GenericBeanDefinition)1 TestBean (org.springframework.beans.testfixture.beans.TestBean)1 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)1