[英]Micronaut Bean Initialization order
我正在使用 micronaut 框架开发一个 java 应用程序。 我想确保我的所有缓存都首先加载(因此使用 @Context 和 @PostConstruct)来加载我的所有缓存。
在加载了所有缓存后,我想加载一个特定的 bean BeanB(确保最后调用它的 @PostConstruct)。
我尝试将 @Requires 用于 BeanB(beans={cache1,cache2} 等,但是在使用 @PostConstruct 完成所有缓存之前调用了 BeanB @PostConstruct。
您可以利用BeanInitializedEventListener
这是我如何理解您的用例的示例:
package com.micronaut.example
import io.micronaut.context.annotation.Factory
import io.micronaut.context.event.BeanInitializedEventListener
import io.micronaut.context.event.BeanInitializingEvent
import org.slf4j.LoggerFactory
import javax.annotation.PostConstruct
import javax.inject.Singleton
class Cache {
companion object {
private val log = LoggerFactory.getLogger(Cache::class.java)
}
fun initialized() {
log.info("initialize")
}
}
class Server(private val cache1: Cache, private val cache2: Cache) {
companion object {
private val log = LoggerFactory.getLogger(Server::class.java)
}
fun start() {
log.info("start")
cache1.initialized()
cache2.initialized()
}
}
@Factory
class ServerFactory {
companion object {
private val log = LoggerFactory.getLogger(ServerFactory::class.java)
}
internal lateinit var cache1: Cache
internal lateinit var cache2: Cache
private lateinit var server: Server
@PostConstruct
fun initialize() {
log.info("initialize")
server = Server(cache1, cache2)
server.start()
}
@Singleton
fun server(): Server {
return server
}
}
@Singleton
class CacheInitializer() : BeanInitializedEventListener<ServerFactory> {
companion object {
private val log = LoggerFactory.getLogger(CacheInitializer::class.java)
}
init {
log.info("constructor")
}
override fun onInitialized(event: BeanInitializingEvent<ServerFactory>): ServerFactory {
log.info("onInitialized")
event.bean.cache1 = Cache()
event.bean.cache2 = Cache()
return event.bean
}
}
测试它:
package com.micronaut.example
import io.micronaut.test.annotation.MicronautTest
import org.junit.jupiter.api.Test
import javax.inject.Inject
@MicronautTest
class AppTest {
@Inject
private lateinit var first: Server
@Test
fun contextLoads() {
}
}
这为您提供了以下日志输出:
INFO i.m.context.env.DefaultEnvironment - Established active environments: [test]
INFO c.micronaut.example.CacheInitializer - constructor
INFO c.micronaut.example.CacheInitializer - onInitialized
INFO com.micronaut.example.ServerFactory - initialize
INFO com.micronaut.example.Server - start
INFO com.micronaut.example.Cache - initialize
INFO com.micronaut.example.Cache - initialize
我希望日志能提供足够的信息,但基本上BeanInitializedEventListener
会在ServerFactory
实例化BeanInitializedEventListener
调用,但在其他任何事情之前。 在这里你可以设置一些参数。 这确保您的缓存是在您的服务器之前创建的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.