如何在Scala对象中使用Spring自动接线(或手动接线)? [英] How to use Spring Autowired (or manually wired) in Scala object?
问题描述
我正在尝试将Spring与Scala结合使用.我知道Autowired可以与Scala类一起使用,但是我正在使用一个需要对象的Web框架,并且我想向其中注入dao.我不知道该怎么做?抱歉,我对Scala还是陌生的,谢谢.
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 wonder how to do this? Sorry, I am quite new to Scala, thanks in advance.
@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>
推荐答案
基本上,您有两个问题:
Basically, you have two problems:
-
属性应该是可变的,即
var
而不是val
Scala object
的所有方法均为static
,而Spring需要实例方法.实际上,Scala在幕后创建了一个名为UserRest$
的实例方法的类,您需要使它的单例实例UserRest$.MODULE$
可用于Spring.
Spring可以将配置应用于预先存在的单例实例,但是它们应该由方法返回,而UserRest$.MODULE$
是一个字段.因此,您需要创建一个返回它的方法.
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>
您可以将<property>
替换为@Autowired
,但由于上述单例实例的问题,因此无法使用@Service
替换手动bean声明.
You can replace <property>
with @Autowired
, but cannot replace manual bean declaration with @Service
due to problems with singleton instance described above.
另请参见:
- What is the Java equivalent of a Scala object?
- 3.3.2.2 Instantiation with a static factory method
这篇关于如何在Scala对象中使用Spring自动接线(或手动接线)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!