简体   繁体   English

SpringBoot 中的 Kotlin - `init` 块的初始化顺序

[英]Kotlin in SpringBoot - initialization order for `init`-blocks

the following situation is in Kotlin and SpringBoot context.以下情况是在 Kotlin 和 SpringBoot 上下文中。 I would like to know if the initialization of Kotlin's init block is executed before or after all dependency injection is executed.我想知道Kotlin的init块的init是在所有依赖注入执行之前还是之后执行。

Intuitively init is executed when the class is created, so it does not wait for the die DI-framework to be ready.直觉上init在创建类时执行,因此它不会等待 die DI 框架准备就绪。 This can lead to potential problems.这可能会导致潜在的问题。

Does anyone have more information or documentation?有人有更多信息或文档吗?

Just taking Spring-Boot as an example:仅以 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")
    }
}

will print the following lines:将打印以下几行:

MyService Init
MyController Init

So the dependency will be initialized first.所以依赖将首先被初始化。 Afterwards the init of the class will be called.之后将调用类的init The init functions will be executed before the constructor of a Kotlin class. init函数将在 Kotlin 类的构造函数之前执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM