【发布时间】:2021-01-23 05:03:13
【问题描述】:
以下情况是在 Kotlin 和 SpringBoot 上下文中。
我想知道 Kotlin 的 init 块的初始化是在所有依赖注入执行之前还是之后执行的。
直观地,init 在创建类时执行,因此它不会等待模具 DI 框架准备好。这可能会导致潜在的问题。
有没有人有更多的信息或文档?
【问题讨论】:
标签: spring-boot kotlin dependency-injection
以下情况是在 Kotlin 和 SpringBoot 上下文中。
我想知道 Kotlin 的 init 块的初始化是在所有依赖注入执行之前还是之后执行的。
直观地,init 在创建类时执行,因此它不会等待模具 DI 框架准备好。这可能会导致潜在的问题。
有没有人有更多的信息或文档?
【问题讨论】:
标签: spring-boot kotlin dependency-injection
以Spring-Boot为例:
package com.example.demo
import org.springframework.stereotype.Controller
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.GetMapping
@Controller
class MyController(private val service: MyService) {
init {
println("MyController Init")
}
@GetMapping("/")
fun foo(): String = "bar"
}
@Service
class MyService {
init {
println("MyService Init")
}
}
将打印以下行:
MyService Init
MyController Init
所以依赖将首先被初始化。之后将调用该类的init。
init 函数将在 Kotlin 类的构造函数之前执行。
【讨论】: