在SpringFramework 5.1中注册同名测试bean
我的生产文件中有以下配置:在SpringFramework 5.1中注册同名测试bean,spring,spring-boot,kotlin,spring-framework-beans,Spring,Spring Boot,Kotlin,Spring Framework Beans,我的生产文件中有以下配置: @Configuration internal class Config { @Bean fun clock() = Clock.systemUTC() } 在测试中: @Configuration class ClockTestConfiguration { @Bean fun clock() = SetableClock() } 我的测试注释: @SpringBootTest( webEnvironment = SpringBootTe
@Configuration
internal class Config {
@Bean
fun clock() = Clock.systemUTC()
}
在测试中:
@Configuration
class ClockTestConfiguration {
@Bean
fun clock() = SetableClock()
}
我的测试注释:
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = [
MyApplication::class,
ClockTestConfiguration::class
]
)
class MyTest {
...
当我使用SpringBoot2.0.5.RELEASE
。升级到2.1.0.RELEASE
后,它在bean注册期间失败
Caused by: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'clock' defined in com.foo.clock.ClockTestConfiguration:
Cannot register bean definition [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=clockTestConfiguration; factoryMethodName=clock; initMethodName=null; destroyMethodName=(inferred);
defined in com.foo.clock.ClockTestConfiguration] for bean 'clock': There is already [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=config; factoryMethodName=clock; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/foo/clock/Config.class]] bound.
at org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition(DefaultListableBeanFactory.java:894)
有没有一种干净的方法覆盖这样的bean?您可以使用
@springbootest
的属性设置spring.main.allow bean definition overriding=true
您可以使用profilesCreate解决方案分离配置。我想知道为什么在使用@springbootest
时,默认情况下它没有设置为true
。默认情况下它没有启用,因为这可能会导致您的测试全部通过,即使您的应用程序由于重复的bean而无法启动。