我的生产文件中有以下配置:

@Configuration
internal class Config {

  @Bean
  fun clock() = Clock.systemUTC()
}

在测试中:

@Configuration
class ClockTestConfiguration {

  @Bean
  fun clock() = SetableClock()
}

My test annotations:

@SpringBootTest(
  webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
  classes = [
    MyApplication::class,
    ClockTestConfiguration::class
  ]
)
class MyTest {
...

当我使用Spring Boot2.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)

Is there a clean way to override such bean?

推荐答案

您可以使用@SpringBootTestproperties属性来设置spring.main.allow-bean-definition-overriding=true.

Kotlin相关问答推荐

如何在Kotlin中模拟www.example.com()?

使用数据存储首选项Kotlin Jetpack Compose

如何进行基于lambda/谓词的两个列表的交集?

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

在 Kotlin 中实现并输入 Either

Criteria Api 中的 Kotlin 泛型

使用 kotlin 流删除 map 中具有某些相似性的值

Kotlin中用于调用常量名称的枚举类方法之间的区别

如何从 kotlin 中的数据类访问 val?

伴随对象在变量更改时更改它的值

compareBy 如何使用布尔表达式在 kotlin 中工作

如何在 IntelliJ 中更改 Kotlin 的this property has a backing field代码编辑器突出显示?

将 Kotlin 类属性设置器作为函数引用

如何从不同的功能发出流量值? Kotlin 协程

为什么 Kotlin Pair 中的条目不可变?

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

Kotlin替换字符串中的多个单词

Android Kotlin .visibility

目前不支持 Gradle 项目的自动库版本更新.请手动更新您的 build.gradle