在Akka Actor中使用AnnotationConfigApplicationContext获取上下文

时间:2015-05-14 19:14:43

标签: spring scala akka

如何获取注释上下文。我正在查看此代码(copied from here):

case object Tick
case object Get
@Named
class CountingService {
  def increment(count: Int) = count + 1
}
@Named
@Scope("prototype")
class Counter @Inject() (countingService: CountingService) extends Actor {

  var count = 0

  def receive = {
    case Tick => count = countingService.increment(count)
    case Get  => sender ! count
  }
}

@Configuration
class AppConfiguration {
  @Bean
  def actorSystem = ActorSystem("Akkaspring")
}

object Akkaspring extends App {
  val ctx = new AnnotationConfigApplicationContext
  ctx.scan("org.typesafe")
  ctx.refresh()

  val system = ctx.getBean(classOf[ActorSystem])

  val counter = system.actorOf(Props().withCreator(ctx.getBean(classOf[Counter])))

  counter ! Tick
  counter ! Tick
  counter ! Tick

  implicit val timeout = Timeout(5 seconds)

  // wait for the result and print it, then shut down the services
  (counter ? Get) andThen {
    case count ⇒ println("Count is " + count)
  } onComplete { _ => system.shutdown() }
}

但是如果我想在另一个Actor中使用计数器怎么办? 例如

class CounterUser extends Actor {
val countingService =  system.actorOf(Props().withCreator(ctx.getBean(classOf[Counter])))
def receive = {
    case Tick => countingService ! Tick
  }
}

如何在其他演员中获取上下文?

如何注入其他AnnotationConfigApplicationContext进行测试?

1 个答案:

答案 0 :(得分:1)

假设from("direct:twitterinternal") .recipientList(simple("twitter://timeline/user?type=direct&user=" + "${body}")) 是一个Spring bean,你可以这样做:

CounterUser

以下是使用Akka扩展程序执行相同操作的另一种方法:https://github.com/bijukunjummen/akka-scala-spring/tree/upgrade-spring