假设我有一个类注入了许多 spring bean:
@Component
open class CoreContext {
@Inject
protected lateinit var bean1 : SomeInterface1
@Inject
protected lateinit var bean2 : SomeInterface2
}
它在context:component-scan
块中定义core.xml
,在传统的 SpringTest 中,它像这样工作得很好:
@RunWith(SpringRunner::class)
@ContextConfiguration(locations = ["classpath:core.xml"])
class CoreContextTest { ... }
现在,我想尝试使用 DSL 样式来定义 bean,并将这些 DSL 定义的 bean 与旧 bean 一起使用:
@Component
class MyBeans : CoreContext() {
val beans = beans {
bean("simpleComparator") {
Comparator<Number> { o1, o2 -> o1.toInt().minus(o2.toInt()) }
}
}
}
MyBeans
位于component-scan
packages 中,并且 IntelliJ 正确检测到它。
但是如何测试这个 simpleComparator 呢?
我尝试@Inject simpleComparator : Comparator<Number>
,但 intelliJ 抱怨No beans of Comparator<Number> type found
。在运行时,它按预期失败。
@RunWith(SpringRunner::class)
@ContextConfiguration(locations = ["classpath:core.xml"])
class MyBeansTest {
@Inject
private lateinit var context: ApplicationContext
// @Inject // No beans of Comparator<Number> type found
// private lateinit var simpleComparator : Comparator<Number>
@Test
fun printBeans() {
logger.info("context = {}", context)
context.beanDefinitionNames.forEach { name ->
logger.info("{}", name)
}
}
}
当我想打印出所有注册的 bean 时,我找不到simpleComparator
bean。
似乎所有相关信息都是基于 SpringBoot 的。但我找不到纯SpringRunner
单元测试示例。谢谢。
版本:
<kotlin.version>1.3.30</kotlin.version>
<spring.version>5.1.4.RELEASE</spring.version>