为什么Kotlin中的弹簧方法注射不起作用?

时间:2019-05-09 21:16:15

标签: java spring kotlin cglib

我尝试使用Spring 5.1.6和Kotlin 1.3.20实现方法注入

当我使用Kotlin方法实现方法注入时,getNotification不返回SchoolNotification的新对象。我得到Kotlin NPE。

@Component
@Scope("prototype")
open class SchoolNotification {
override fun toString(): String {
    return Objects.toString(this)
    }
}

StudentServices:

@Component
open class StudentServices {
@Lookup
fun getNotification(): SchoolNotification {
    return null!!
    }
 }

当我用Java编写相同的代码时,一切都很好

@Component
@Scope("prototype")
public class SchoolNotification {

}

StudentServices:

@Component
public class StudentServices {

@Lookup
public SchoolNotification getNotification() {
    return null;
    }
}

主要

fun main() {
  val ctx = AnnotationConfigApplicationContext(ReplacingLookupConfig::class.java)
  val bean = ctx.getBean(StudentServices::class.java)
  println(bean.getNotification())
  println(bean.getNotification())
  ctx.close()
}

使用Kotlin怎么办?

1 个答案:

答案 0 :(得分:2)

除了创建类open外,还需要创建方法open,否则该方法仍标记为final,Spring将无法提供其方法。自己在子类中的实现:

@Lookup
open fun getNotification(): SchoolNotification {
    return null!!
}