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

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

    All that's actually necessary is that you define your object as a class, rather than an object. That way Spring will instantiate it.

     @Service
        object UserRest extends RestHelper {
            @Autowired
            @BeanProperty
            val userRepository: UserRepository = null;
    
            .....
        }
    <beans>
             .....
             <bean id="userRest" class="com.abc.rest.UserRest" >
                  <!--- this is my attempt to manually wire it --->
                  <property name="userRepository" ref="userRepository"/>
             </bean>
        </beans>
    

    Changing the "val" to "var" is unnecessary (Spring uses reflection, which ignores immutability). I'm pretty sure that that @BeanProperty is also unnecessary (Spring will assign to the underlying field, reflectively).

    0 讨论(0)
  • 2020-12-28 20:18

    Basically, you have two problems:

    • Property should be mutable, i.e. var rather than val

    • All methods of Scala object are static, whereas Spring expects instance methods. Actually Scala creates a class with instance methods named UserRest$ behind the scene, and you need to make its singleton instance UserRest$.MODULE$ available to Spring.
      Spring can apply configuration to preexisting singleton instances, but they should be returned by a method, whereas UserRest$.MODULE$ is a field. Thus, you need to create a method to return it.

    So, something like this should work:

    object UserRest extends RestHelper {
       @BeanProperty
       var userRepository: UserRepository = null;
    
       def getInstance() = this
       ...
    }
    

    .

    <bean id="userRest" 
        class="com.abc.rest.UserRest" 
        factory-method = "getInstance">
        <property name="userRepository" ref="userRepository"/>
    </bean>
    

    You can replace <property> with @Autowired, but cannot replace manual bean declaration with @Service due to problems with singleton instance described above.

    See also:

    • What is the Java equivalent of a Scala object?
    • 3.3.2.2 Instantiation with a static factory method
    0 讨论(0)
提交回复
热议问题