Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override a scoped bean for tests?

I have this bean in my Spring Java config:

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

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

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

I get a "Desktop" scoped mocked bean :-(

How do I make Spring "forget" the @Scope annotation?

PS: It works when I don't use @Import and use copy&paste but I don't want to do that.

like image 291
Aaron Digulla Avatar asked Nov 12 '22 12:11

Aaron Digulla


1 Answers

The problem seems to be in ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod() that uses ScopedProxyCreator.createScopedProxy() static method to create the scoped 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();
    }

As the BeanDefinitionHolder returns a RootBeanDefinition instead of ConfiguratioClassBeanDenition the scoped proxy bean definition (ie, the ScopedProxyFactoryBean) cannot be overriden by another Java Configuration class.

A workaround could be declaring the scoped beans to override in a xml configuration file and importing it with @ImportResource.

like image 52
Jose Luis Martin Avatar answered Nov 15 '22 06:11

Jose Luis Martin