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

后端 未结 8 1646
栀梦
栀梦 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:05

    In addition to https://stackoverflow.com/a/8344485/5479289, it's also possible to add scala package object to Spring context, as well as scala object, using factory method. Compiled package object is usual java class named package, so you can add it to Spring context. After that you will have all Spring's possibilities inside this object, i.e @Autowired, @Value, manual wiring etc.

    Test package:

    package my.module
    
    package object A {
      def getInstance = this
    
      @Autowired
      private val b: B = null
    }
    

    And spring context xml is:

    
      ...
      
      ...
    
    

提交回复
热议问题