无法通过使用 kotlin 开放类构造函数实例化 spring bean 属性

open class XService( // this is open because spring-cglib
    val yService: YService 
) {
    fun doX() { 
       yService.doY()
    }
}

interface YService {
  //method definitions
}

从上面可以看出,XService 依赖于 YService 接口。我试图通过提供 YService 接口的两个不同实现来实例化两个不同的 bean,比如说 AService:YServiceBService:YService

@Configuration
class SomeBeans{

  @Bean
  fun firstXService(aService:AService):XService {//AService is a @Service annotated class,so it is perfectly being injected here,aka argument is not null
     return XService(
       yService = aService
     )
   }
  
  @Bean
  fun secondXService(bService:BService):XService {//BService is a @Service annotated class,aka argument is not null
     return XService(
       yService = bService
     )
   }

}

上面是完美实例化bean,可以看到这两个bean都位于上下文中。

但是当我碰巧运行一些集成测试(使用 spring 上下文)时,每次调用 xService.doX() 都会失败并显示 NPE:null,这是因为 yService 为 null。

知道这里发生了什么吗?引擎盖下发生了什么?

提前致谢!

magss 回答:无法通过使用 kotlin 开放类构造函数实例化 spring bean 属性

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/695465.html

大家都在问