Skip to content

Instantly share code, notes, and snippets.

@stella6767
Created July 28, 2022 05:31
Show Gist options
  • Save stella6767/269c6bc115b5e32cf276f6541b56243b to your computer and use it in GitHub Desktop.
Save stella6767/269c6bc115b5e32cf276f6541b56243b to your computer and use it in GitHub Desktop.
Accessing spring beans in static method
@Configuration(proxyBeanMethods = false)
class BeanRegistry : ApplicationContextAware {
companion object {
private lateinit var applicationContext: ApplicationContext
// 타입으로 빈을 가져옵니다
fun <T : Any> getBean(type: KClass<T>): T =
applicationContext.getBean(type.java)
// 이름과 타입으로 빈을 가져옵니다
fun <T : Any> getBean(name: String, type: KClass<T>): T =
applicationContext.getBean(name, type.java) //type이 중복될 때 name으로 구분
}
override fun setApplicationContext(applicationContext: ApplicationContext) {
BeanRegistry.applicationContext = applicationContext
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment