spring - spring 可以对绑定(bind)进行类似 guice 的覆盖吗?

标签 spring

在 Guice 中,我有一个带有绑定(bind)的 ProductionModule。在我的测试中,我可以加载该模块以及一个用模拟对象覆盖一些生产绑定(bind)的模块。我如何在 Spring 做这样的事情......

例如,在测试文件中加载 production-spring.xml,然后在 test-spring.xml 中加载测试,这只会覆盖 production-spring.xml 中的一些绑定(bind)

这会测试集成并确保 production-spring.xml 中的更改不会破坏内容。这些是比测试单元更自动化的集成测试,并且工作得非常好。

最佳答案

您可以通过列出多个 xml 文件来覆盖 beans。后面文件中的 Bean 将覆盖之前加载的 Bean。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
      locations = {"classpath:prodDB.xml", 
                   "classpath:applicationContext.xml", 
                   "classpath:testDb.xml"})
public class SpringTest {

    @Autowired
    protected DataSource dataSource; //uses the datasource from testDb.xml

}

因此,在这种情况下,testDB.xml 会覆盖 prodDb.xml 中配置的数据源。即使您也不使用 SpringJUnit4ClassRunner,这也适用:

new ClassPathXmlApplicationContext(new String[]
        {"classpath:prodDb.xml",
         "classpath:testDb.xml"});

使用类似 Constretto 的工具您可以对带注释的 bean 执行相同的操作:

@Service
public class FooService...

@Service
@Environment("test")
public class FakeFooService ...

现在,如果您在类上使用 @Environment("test") 注释运行测试,则将使用 FakeFooService。

关于spring - spring 可以对绑定(bind)进行类似 guice 的覆盖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489274/

相关文章:

java - Spring Controller 不工作

java - Spring Boot 中的 Stripe 示例 Java 服务器?不兼容的类型 : Optional<StripeObject> cannot be converted to Source

java - Spring Boot - 使用自定义 PreAuthorize 表达式和身份验证测试 Rest Api

java - 无法在 Spring boot 中使用 @bean 内的 @value

java - 如何在 Controller 中使用 @RequestParam 获取 Map<String, String[]> 数据?

java - Spring Stomp over Websocket : Message/Buffer/Cache/Stream limits

spring - 在 Kotlin 上添加 Spring Security 后测试 Spring Controller POST 方法

java - spring boot starter security post 方法不起作用

java - Spring MVC url 模式语法

Spring JPA : Locking parent row when inserting one to many child record