如何在Spring中@Autowire scala对象

时间:2015-12-30 11:37:33

标签: java spring scala dependency-injection

请考虑以下代码:

TimeSeries.scala

trait TimeSeries {
   def someMethod()
}

object TimeSeries extends TimeSeries {
   def someMethod() = { new someOtherMethod() }
}

META-INF /弹簧/ series.xml

<bean id="timeSeries" class="com.people.user.data.TimeSeries" />

SomeService.java

class SomeService
{
   @Autowired
   private TimeSeries timeSeries;

   TimeSeries.someMethod(); //Compile Time Error
}

这里要注意的第一件事是TimeSeries.scala文件有TimeSeries Object所以我假设它有一个类范围,因此我可以直接通过TimeSeries.someMethod();调用它的方法而不实例化它

但事实并非如此。我这样做会遇到编译时错误。

Cannot make a static reference to the non-static method `someMethod`

所以我觉得要引入@Autowiring以便Spring可以自动实例化它。 但是,这并不是说错误:

<bean id="timeSeries" class="com.people.user.data.TimeSeries" />

错误是:TimeSeries is an interface and not a class.

我理解这一点,因此将对象类的名称更改为:

object TimeSeriesImpl extends TimeSeries {
       def someMethod() = { new someOtherMethod() }
    }

还更改了spring XML:

<bean id="timeSeries" class="com.people.user.data.TimeSeriesImpl" />

但是现在在实例化scala类时遇到错误。

看起来Spring并不了解如何使用上述配置实例化Scala类。

这是LOG:

LOG:

Instantiation of bean failed; nested exception 
is     org.springframework.beans.
BeanInstantiationException: 
Could not instantiate bean class [com.people.user.data.TimeSeries]: 
No default constructor found; nested exception 
is  java.lang.NoSuchMethodException: com.people.user.
data.TimeSeries.<init>()

1 个答案:

答案 0 :(得分:1)

  

无法对非静态方法someMethod

进行静态引用

问题是您无法直接致电TimeSeries.someMethod();

其中, TimeSeries是scala对象,someMethod()是该对象的方法。

正确的方法是:

TimeSeries$ timeSeries = TimeSeries$.MODULE$; timeSeries.someMethod();