【问题标题】:Difference between @PropertySource and @DynamicPropertySource in Spring FrameworkSpring框架中@PropertySource和@DynamicPropertySource的区别
【发布时间】:2020-03-28 21:45:50
【问题描述】:

@DynamicPropertySource 属性是作为 Spring 框架 5.2.5 版的一部分添加的。 official documentation 表示:

此注解及其支持基础设施最初是 旨在允许来自基于测试容器的测试的属性 容易暴露于 Spring 集成测试。但是,此功能可能 也可用于任何形式的外部资源,其生命周期为 在测试的 ApplicationContext 之外维护。

还有一个基本的例子:

@SpringJUnitConfig(...)
@Testcontainers 
class ExampleIntegrationTests { 
@Container 
static RedisContainer redis = new RedisContainer(); // ...
@DynamicPropertySource 
static void redisProperties(DynamicPropertyRegistry registry) { 
registry.add("redis.host", redis::getContainerIpAddress);
 registry.add("redis.port", redis::getMappedPort);
 } }

但是,我不明白...当我们拥有行为相同的 @PropertySource 时,这个新注释的用例是什么?

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    我最终在this Github 问题中找到了答案,该问题导致@DynamicPropertySource 注释的提交。

    注解@PropertySource:

    主要用于使用Spring环境从属性文件中读取 界面

    可以在this nice article 中找到其使用示例。

    @DynamicPropertySource 用于:

    更容易从其他东西设置配置属性 这是作为运行集成测试的一部分进行引导的。

     这还有助于使用测试容器设置集成测试,摆脱大量样板代码。

    虽然在这种情况下缺少文档,但可以在 Spring.io 网站上的 this blog 找到一篇非常好的文章。 根据上面的文章,例子是:

    @SpringBootTest
    @Testcontainers
    @ContextConfiguration(initializers = ExampleIntegrationTests.Initializer.class)
    
    class ExampleIntegrationTests {
    
        @Container
        static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
    
        static class Initializer implements
                ApplicationContextInitializer<ConfigurableApplicationContext> {
    
            @Override
            public void initialize(ConfigurableApplicationContext context) {
                TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getBoltUrl())
                        .applyTo(context.getEnvironment());
            }
    
        }
    
    }
    

    @DynamicPropertySource 注解可以使上面的测试更清晰,消除样板代码,如下例所示:

    @SpringBootTest
    @Testcontainers
    class ExampleIntegrationTests {
    
        @Container
        static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
    
        @DynamicPropertySource
        static void neo4jProperties(DynamicPropertyRegistry registry) {
            registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多