【发布时间】:2020-11-24 02:16:45
【问题描述】:
我正在使用 TestNG 和 Spring Framework(以及 Spring Boot)编写测试,并且正在运行到应用程序上下文中,无法找到特定的配置属性 bean。
设置涉及两个独立的配置,均由测试引用。导致问题的设置的简单表示将涉及以下配置:
@EnableConfigurationProperties
public class SomePropertyConfiguration {
@Bean(name = "someConfiguration")
@ConfigurationProperties(prefix = "test.prefix")
public CustomPropertyClass customPropertyClass(){
return new CustomPropertyClass();
}
}
@Configuration
public class SomeConfiguration {
public ISomethingApi somethingApi(CustomPropertyClass customPropertyClass){
return new SomethingApi(customPropertyClass.getProperty());
}
}
测试设置很简单,只是为了测试几个基本属性:
@TestPropertySource("classpath:/test.properties")
@ContextConfiguration(classes = { SomePropertyConfiguration.class, SomeConfiguration.class })
public class SomethingApiTest extends AbstractTestNGSpringContextTests {
@Inject
private ISomethingApi somethingApi;
@Test
public void test(){
// Do stuff
}
}
这些设置的最终结果是SomethingApi 的配置无法找到CustomPropertyClass 类型的有效bean。
值得注意的是,如果从测试中删除SomeConfiguration,并直接将CustomPropertyClass 注入测试中,一切正常并且属性是预期值,这是最令人困惑的问题 - 所以某些东西似乎导致 spring 无法正确处理 bean 的接线顺序。我在其他项目中也有类似的设置,它们按预期运行,但我找不到任何可能导致这种行为的有意义的差异(两个项目都在同一个主要版本的 Spring 和 Spring Boot 上)
编辑:
我在SomePropertyConfiguration 上尝试了使用和不使用@Configuration,结果没有任何变化。在这个工作引用的另一个项目中,属性配置类不包含该显式注释,因此我在上面的主要示例中将其省略了。我还尝试在第二个配置中使用属性 bean 的 @Autowired 字段并以这种方式引用它作为依赖项,而不是作为参数(以防影响布线顺序或其他东西),这也对结果。
我正在使用 Spring 框架 5.1.7.RELEASE 和 Spring Boot 2.0.9.RELEASE
【问题讨论】:
-
你通常应该说
@EnableConfigurationProperties(CustomPropertyClass.class)。 -
我的印象是,这是一个选项,而不是在带有
@Bean的函数中声明以使其连接 - 在这种情况下,我在函数上使用@ConfigurationProperties和@Bean,因为对于不同的配置实例,将使用不同的前缀重新使用相同的属性类(本示例中不存在,因为问题项目中尚未设置,为了简单起见,我试图将示例简化为主要元素描述问题) -
啊,我明白了(你没有包括你的实际每次点击费用);这是一个选项(不是最常见的,但它确实适用于您的情况)。我注意到您的
SomePropertyConfigurationsn-p 这里没有@Configuration;你能确认它在你的应用程序中吗? -
它目前不包括
@Configuration,但我确实尝试了该设置(抱歉,我的意思是包含我迄今为止尝试过但忘记的几个变体的列表,我将编辑问题)
标签: java spring spring-boot testng