Spring Boot测试@ConfigurationProperties不绑定字段

Mis*_*sus 5 java spring spring-boot spring-boot-test

各位晚上好。我有一个专为与属性绑定而设计的类。在标记为 的类中@Configuration,我将这个 bean 对象设置为:

\n\n
// Into TargetConfiguration class\n\n@Bean("someBeanName")\n@ConfigurationProperties("some.path")\npublic beanProperties() {\n    return new BeanProperties();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想测试此配置的所有功能,为此我创建一个测试类,例如:

\n\n
@WebFluxTest\n@TestPropertySource("classpath:test.properties")\n@ContextConfiguration(classes = {TargetConfiguration.class})\nclass Test {...}\n
Run Code Online (Sandbox Code Playgroud)\n\n

问题是它将BeanProperties包含空字段,但如果我创建一些其他字段并通过inOtherBeanProperties注册它,那么它通常会被填充,但对于我可以\xe2\x80\x99t 这样做,因为这个bean取决于测试中的属性。特性。另外,如果我通过配置创建这个 bean ,那么它将被填充到...@EnableConfigurationPropertiesTargetConfigurationBeanProperties@TestConfiguration

\n\n

任何帮助表示赞赏。

\n\n

UPD-1:第一个假设 - 我注册了一些使用名为 的注释扩展BeanDefinitionRegistryPostProcessor@DependsOnRegistratorClass。我不知道为什么,但是如果我添加@DependsOnRegistratorClass,我会BeanProperties立即构造而不绑定(并传递给想要接收此消息的其他方法BeanProperties)。如果我删除这个注释,RegistratorClass初始化第一个注释,我的BeanProperties将正常构造并绑定到属性。

\n

Phi*_*ebb 3

ABeanDefinitionRegistryPostProcessor在生命周期的早期初始化,旨在用于添加其他 bean 定义。在您在https://github.com/spring-projects/spring-boot/issues/21584发布的示例代码中,您声明beanGenerator依赖于someOtherBeanUser. 依次someOtherBeanUser注入beanUser. 这意味着someOtherBeanUserbeanUser很早就被注入。

配置绑定的工作方式是通过ConfigurationPropertiesBindingPostProcessor. 通过触发早期初始化,您将强制 Spring 在注册beanUser之前创建。ConfigurationPropertiesBindingPostProcessor这意味着不能应用任何绑定。

完整的示例应用程序将有助于确定为什么您的属性没有被绑定,但我相信添加@EnableConfigurationPropertiesTargetConfiguration测试类本身可以修复它。