How to override bean tags for tests?

I have this bean in my Spring Java configuration:

@Bean
@Scope( proxyMode=ScopedProxyMode.TARGET_CLASS, value=SpringScopes.DESKTOP )
public BirtSession birtSession() {
    return new BirtSession();
}

For tests, I need a layout without scope (in the test, there is no "Desktop" area). But when I create my test configuration, which imports the above configuration and contains:

@Bean
public BirtSession birtSession() {
    return new MockSession();
}

I get a "Desktop" with a fake bean: - (

How to make Spring forget the annotation @Scope?

PS: It works when I do not use @Importand use copy & paste, but I do not want to do this.

+5
source share
2 answers

The problem is ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(), which uses a static method ScopedProxyCreator.createScopedProxy()to create a bean definition:

// replace the original bean definition with the target one, if necessary
        BeanDefinition beanDefToRegister = beanDef;
        if (proxyMode != ScopedProxyMode.NO) {
            BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
                    new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS);
            beanDefToRegister = proxyDef.getBeanDefinition();
    }

BeanDefinitionHolder RootBeanDefinition ConfiguratioClassBeanDenition, scxy bean (.. ScopedProxyFactoryBean) Java.

, beans xml @ImportResource.

+1

Spring , , Spring "" , , . Spring . / bean.

:

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;

public class MockSpringScope implements org.springframework.beans.factory.config.Scope {

    private Map<String, Object> objects = new HashMap<String, Object>();

    @Override
    public Object get( String name, ObjectFactory<?> objectFactory ) {
        Object result = objects.get( name );
        if( null == result ) {
            result = objectFactory.getObject();
            objects.put( name, result );
        }
        return result;
    }

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

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

    @Override
    public Object resolveContextualObject( String key ) {
        // NOP
        return null;
    }

    @Override
    public String getConversationId() {
        // NOP
        return null;
    }

}

" ". Spring .

0

All Articles