【问题标题】:Spring Boot: How to inject the same instance of a prototype scoped bean into a Spring Boot Test?Spring Boot:如何将原型范围 bean 的相同实例注入 Spring Boot 测试?
【发布时间】:2019-08-05 11:55:29
【问题描述】:

我有一个服务类,它使用以下列方式声明的原型作用域 bean:

@Bean
@Scope(scopeName = SCOPE_PROTOTYPE, proxyMode = TARGET_CLASS)
MyBean myBean() {...}

我有一个如下所示的集成测试:

@SpringBootTest
@ExtendWith(SpringExtension.class)
class MyServiceTest {
    @Autowired
    MyBean myBean;
    // tests follow here
}

问题:我在测试中需要完全相同的 MyBean 实例,但 Spring 注入了一个不同的实例,因为 bean 的范围是“原型”。

问题:如何将原型作用域 bean 的相同实例注入测试中?

注意:我无法更改 bean 的范围声明。

【问题讨论】:

    标签: java spring spring-boot junit spring-boot-test


    【解决方案1】:

    您有两种方法。

    覆盖 MyBean 使其成为单例 bean:

    @TestConfiguration
    public class OverrideBeanConfigurationForTest {
    
        @Bean
        @Scope(scopeName = SCOPE_SINGLETON)
        MyBean myBean() {...}
    }    
    

    或覆盖它以始终返回相同的 bean:

    @TestConfiguration
    public class OverrideBeanConfigurationForTest {
    
        MyBean myBean;
    
        @Bean
        @Scope(scopeName = SCOPE_PROTOTYPE, proxyMode = TARGET_CLASS)
        MyBean myBean() {
          if (myBean == null){ 
             myBean = new MyBean(...),
          }
          return myBean;
        }
    }    
    

    现在在您的 Spring Boot 测试中导入此配置,并指定属性 spring.main.allow-bean-definition-overriding=true,因为默认情况下为 false

    @SpringBootTest({"spring.main.allow-bean-definition-overriding=true"})
    @ExtendWith(SpringExtension.class)
    @Import(OverrideBeanConfigurationForTest.class)
    class MyServiceTest {
        @Autowired
        MyBean myBean;
        // tests follow here
    }
    

    经过测试并且有效。

    【讨论】:

      【解决方案2】:

      如果你不能改变任何东西并且你坚持直接注入 bean 那是不可能的。

      文档明确指出:

      bean 部署的非单例原型范围导致每次对特定 bean 发出请求时都会创建一个新的 bean 实例。也就是说,bean 被注入到另一个 bean 中,或者您通过容器上的 getBean() 方法调用来请求它。 通常,您应该对所有有状态 bean 使用原型范围,对无状态 bean 使用单例范围.

      你正在将它注入另一个 bean。

      Prototype scoped beans

      【讨论】:

        猜你喜欢
        • 2019-07-28
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2015-03-04
        • 1970-01-01
        • 2020-05-11
        • 2013-06-14
        相关资源
        最近更新 更多