[英]Spring Bean Unable to Locate Configuration Properties Bean
我正在使用 TestNG 和 Spring 框架(以及 Spring 引导)编写测试,并且正在运行无法找到特定配置属性 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 引导的相同主要版本上)
编辑:
我在SomePropertyConfiguration
上尝试过使用和不使用@Configuration
,结果没有任何变化。 在与此工作相关的另一个项目中,属性配置 class 不包含该显式注释,因此我在上面的主要示例中将其省略了。 我还尝试在第二个配置中使用属性 bean 的@Autowired
字段,并以这种方式为依赖项引用它,而不是作为参数(以防影响布线顺序或其他东西),这对结果也没有影响.
我正在使用 Spring 框架5.1.7.RELEASE
和 Spring 启动2.0.9.RELEASE
经过一些额外的调查,我在日志中发现了以下内容
a definition for bean 'someConfiguration' already exists. This top-level bean definition is considered as an override
事实证明,在这种情况下,我的项目中的命名约定导致了属性类 bean 的名称与项目的整体配置 bean 之间的冲突。 bean 和配置类似乎共享一个命名空间,如果它们发生冲突,则不会(直接)导致崩溃/错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.