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

Getting context using AnnotationConfigApplicationContext in Akka Actor

如何获取注释上下文。我正在查看这段代码 (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 进行测试?

假设 CounterUser 是一个 Spring bean,你可以这样做:

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

这是使用 Akka 扩展来实现相同目的的另一种方法:https://github.com/bijukunjummen/akka-scala-spring/tree/upgrade-spring