如何覆盖作用域的scoped bean?

Aar*_*lla 5 proxy spring scope javabeans

我的Spring Java配置中有这个bean:

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

对于测试,我需要一个没有范围的模拟(测试中没有"桌面"范围).但是,当我为我的测试创建配置时,它会导入上述配置并包含:

@Bean
public BirtSession birtSession() {
    return new MockSession();
}
Run Code Online (Sandbox Code Playgroud)

我得到一个"桌面"范围模拟豆:-(

如何让Spring"忘记" @Scope注释?

PS:当我不使用@Import并使用复制和粘贴时,它可以工作,但我不想这样做.

Jos*_*tin 1

问题似乎在于ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod()使用ScopedProxyCreator.createScopedProxy()静态方法创建作用域 bean 定义:

// 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();
    }
Run Code Online (Sandbox Code Playgroud)

由于BeanDefinitionHolder返回的是 aRootBeanDefinition而不是ConfiguratioClassBeanDenition作用域代理 bean 定义(即ScopedProxyFactoryBean),因此不能被另一个 Java 配置类覆盖。

解决方法可以是在 xml 配置文件中声明要覆盖的作用域 bean 并使用以下命令导入它@ImportResource.