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

后端 未结 8 1650
栀梦
栀梦 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;
    
            .....
        }
    
             .....
             
                  
                  
             
        
    

    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).

提交回复
热议问题