How to use Spring Autowired (or manually wired) in Scala object?

后端 未结 8 1647
栀梦
栀梦 2020-12-28 19:12

I am trying to use Spring with Scala. I know Autowired works with Scala class, but I am using a web-framework that requires an object and I want to inject a dao into it. I w

8条回答
  •  再見小時候
    2020-12-28 20:11

    None of the previous answears worked for me, but after some struggle I could solve it like this:

    @Service
    class BeanUtil extends ApplicationContextAware {
    
        def setApplicationContext(applicationContext: ApplicationContext): Unit = BeanUtil.context = applicationContext
    
    }
    
    object BeanUtil {
        private var context: ApplicationContext = null
    
        def getBean[T](beanClass: Class[T]): T = context.getBean(beanClass)
    }
    

    an then the object:

    object MyObject {
        val myRepository: MyRepository = BeanUtil.getBean(classOf[MyRepository])
    }
    

提交回复
热议问题