Quarkus Kotlin 初始化块被多次调用。

huangapple go评论56阅读模式
英文:

Quarkus Kotlin init block called multiple times

问题

我正在尝试在Quarkus框架中使用Kotlin。我需要在应用程序启动时初始化一些值,所以我使用了Kotlin的init和Quarkus的@Startup。我按照以下方式操作:

@Startup
@ApplicationScoped
class Initializer() {

    init {
        println("初始化变量")
    }

}

我期望字符串"初始化变量"只会被打印一次,但它被打印了两次。似乎Quarkus多次初始化了带有@ApplicationScoped注解的相同类。

我需要初始化只执行一次,否则在代码中尝试使用初始化变量时会出现引用问题。这是正确的方式吗?还有其他方法吗?

英文:

I am trying to use Kotlin with the Quarkus framework. I need to initialize some values at application startup so I have used init from Kotlin and @Startup from Quarkus.

I do as following:

@Startup
@ApplicationScoped
class Initializer() {

    init {
        println("Init Variables")
    }

}

I expected that the string Init Variables would be printed only once time, but it was printed two times. It seems that Querkus initialize the same classes annotated with @ApplicationScoped multiple times.

I need that the initialization is executed only once otherwise I have reference trouble when I am trying to use initialized variables in the code. Is it the correct way?There is another way do that?

答案1

得分: 1

以下是翻译好的部分:

有两种方法的混合。在 Kotlin 中,init 将在类初始化后被调用,可以将其视为默认构造函数(如果有其他构造函数,它们将调用此默认构造函数)。
一种选择是使用 @Observes startupEvent: StartupEvent,例如:

import io.quarkus.runtime.StartupEvent
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.event.Observes

@ApplicationScoped
class Initializer() {

    fun myInit(@Observes startupEvent: StartupEvent) {
        println("Init Variables")
    }
    
}

如果真的想要,仍然可以拥有 init 方法,因为这个 @Observes 将强制初始化 bean,并触发 init 方法。

英文:

There's a mix up of two approaches. In Kotlin, init will be called once the class is initialized, think about it as a default constructor(and if there're other constructors, they'll call this default constructor).
One option is to use @Observes startupEvent: StartupEvent, e.g:

import io.quarkus.runtime.StartupEvent
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.event.Observes


@ApplicationScoped
class Initializer() {

    fun myInit(@Observes startupEvent: StartupEvent) {
        println("Init Variables")
    }
    
}

You can still have init method if you really want, since this @Observes will force-init the bean and this will trigger the init method.

huangapple
  • 本文由 发表于 2023年6月8日 23:26:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定