Scala和Spring - 棘手的案例?

时间:2014-03-13 16:00:55

标签: spring scala

我想使用factory-method使用Spring实例化一个bean。 但是,诀窍是我想在我的工厂方法中访问当前的ApplicationContext

这是我尝试过的代码:

object ActorSystemFactory {

  var applicationContext: ApplicationContext = _

  def createActorSystem = {
    val system = ActorSystem("AkkaScalaSpring")
    SpringExtensionImpl(system)(applicationContext) //need applicationContext here
    system
  }
}

class ActorSystemFactory extends ApplicationContextAware {

  //Spring warns that createActorSystem does not exist here!! and it is...right
  //Indeed, it is present in the companion object to make it "static" equivalent.    

  def setApplicationContext(applicationContext: ApplicationContext) {
    ActorSystemFactory.applicationContext = applicationContext
  }

}

我在xml中的声明:

<bean id="actorSystem" class="com.myPackage.ActorSystemFactory" factory-method="createActorSystem">
</bean>

关于ActorSystemFactory课程中的评论,如何处理案例?

2 个答案:

答案 0 :(得分:0)

spring bean默认为singleton。你可以让你的actor系统直接在类中实例化,不需要对象

答案 1 :(得分:0)

好的,所以我成功了。

事实上,现在我不使用静态工厂方法技术,而是使用实例工厂方法技术:

class ActorSystemFactory extends ApplicationContextAware {

  def createActorSystem = {
    val system = ActorSystem("AkkaScalaSpring")
    SpringExtensionImpl(system)
    system
  }

  def setApplicationContext(applicationContext: ApplicationContext) {
    ActorSystemFactory.applicationContext = applicationContext
  }
}

object ActorSystemFactory {

  var applicationContext: ApplicationContext = _

}



<bean id="actorSystemFactory" class="myPackage.ActorSystemFactory"/>

<bean id="actorSystem" factory-bean="actorSystemFactory" factory-method="createActorSystem" />

http://docs.spring.io/spring/docs/3.0.x/reference/beans.html)(无论是Spring的版本)

整体按预期工作。