@Singleton
@Bean(typed = [Engine::class]) // (1)
class V8Engine : Engine { // (2)
override fun start(): String {
return "Starting V8"
}
override val cylinders: Int = 8
}
@Bean(typed=..) 用于只允许注入接口引擎而不是具体类型
该类必须实现typed定义的类或接口,否则会出现编译错误
以下测试演示了使用编程查找和 BeanContext API 进行类型化的行为:
Java
Groovy
Kotlin
@MicronautTest
public class EngineSpec {
@Inject
BeanContext beanContext;
@Test
public void testEngine() {
assertThrows(NoSuchBeanException.class, () ->
beanContext.getBean(V8Engine.class) // (1)
);
final Engine engine = beanContext.getBean(Engine.class); // (2)
assertTrue(engine instanceof V8Engine);
}
}
class EngineSpec extends Specification {
@Shared @AutoCleanup
ApplicationContext beanContext = ApplicationContext.run()
void 'test engine'() {
when:'the class is looked up'
beanContext.getBean(V8Engine) // (1)
then:'a no such bean exception is thrown'
thrown(NoSuchBeanException)
and:'it is possible to lookup by the typed interface'
beanContext.getBean(Engine) instanceof V8Engine // (2)
}
}
@MicronautTest
class EngineSpec {
@Inject
lateinit var beanContext: BeanContext
@Test
fun testEngine() {
assertThrows(NoSuchBeanException::class.java) {
beanContext.getBean(V8Engine::class.java) // (1)
}
val engine = beanContext.getBean(Engine::class.java) // (2)
assertTrue(engine is V8Engine)
}
}