为什么 spring 方法注入在 Kotlin 中不起作用?
Why doesn't spring method injection work in Kotlin?
我尝试使用 Spring 5.1.6 和 Kotlin 1.3.20
实现方法注入
当我使用 Kotlin 方法实现方法注入时,getNotification 不是 return SchoolNotification 的新对象。我得到了 Kotlin NPE。
@Component
@Scope("prototype")
open class SchoolNotification {
override fun toString(): String {
return Objects.toString(this)
}
}
学生服务:
@Component
open class StudentServices {
@Lookup
fun getNotification(): SchoolNotification {
return null!!
}
}
当我用 Java
编写相同的代码时一切正常
@Component
@Scope("prototype")
public class SchoolNotification {
}
学生服务:
@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 时做错了什么?
除了让你的classopen
,你还需要让你的方法open
,否则方法仍然被标记为final
和[=17] =] 将无法在 subclass:
中为其提供自己的实现
@Lookup
open fun getNotification(): SchoolNotification {
return null!!
}
我尝试使用 Spring 5.1.6 和 Kotlin 1.3.20
实现方法注入当我使用 Kotlin 方法实现方法注入时,getNotification 不是 return SchoolNotification 的新对象。我得到了 Kotlin NPE。
@Component
@Scope("prototype")
open class SchoolNotification {
override fun toString(): String {
return Objects.toString(this)
}
}
学生服务:
@Component
open class StudentServices {
@Lookup
fun getNotification(): SchoolNotification {
return null!!
}
}
当我用 Java
编写相同的代码时一切正常@Component
@Scope("prototype")
public class SchoolNotification {
}
学生服务:
@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 时做错了什么?
除了让你的classopen
,你还需要让你的方法open
,否则方法仍然被标记为final
和[=17] =] 将无法在 subclass:
@Lookup
open fun getNotification(): SchoolNotification {
return null!!
}