1. Introduction

After the introduction tutorial to Akka for java with examples of Javier we will see how we are able to delegate the creation of Akka actors to Spring so that we can use the features that the framework offers us.
This tutorial assumes that you already know the basic principles of Akka shown in the tutorial described above.

2. Environment

The tutorial is written using the following environment:

  • Hardware: Portable MacBook Pro Retina 17 ‘(2.93 Ghz Intel Core 2 Duo, 8GB DDR3).
  • Operating System: Mac OS Yosemite 10.10.3
  • Development environment: IntelliJ IDEA 14

3. Project creation

The first thing we need is to create a new maven project, in which we will have a pom.xml similar to this one:

NOTE: The project is built with Spring boot given the simplicity of startup and configuration that provides

pom.xml
<description>Integration project of akka with spring</description>
<!– lookup parent from repository –>

This file has no mystery, the most important thing is to add the Akka repository and the dependency.

4. Communication between the context of Spring and Akka’s ActorSystem

It is at this point that we will create the “communication bridge” between the application context of Spring and the Akka actor system, and we will delegate the creation of actors in Spring.

To be able to use the Spring application context and let it create and link our actors, we need to store it in a place that is easily accessible to the Akka actor system.
For this purpose, Akka provides akka extension , a tool that allows us to add features to Akka.
These extensions will only be loaded once by ActorSystem, which will be managed by Akka. The potentiality of the extensions of Akka are very large, in fact many characteristics of Akka are implemented using the extensions system.

The extension has two main parts: the SpringExtension class that defines the methods used by Akka to create the extension for a given ActorSystem, and the SpringExt class that defines the available methods and fields of the extension.

SpringExtension.java
public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringExt> {
public static SpringExtension SpringExtProvider = new SpringExtension();
public SpringExt createExtension(ExtendedActorSystem system) {
public static class SpringExt implements Extension {
private volatile ApplicationContext applicationContext;
public void initialize(ApplicationContext applicationContext) {
public Props props(String actorBeanName) {
return Props.create(SpringActorProducer.class, applicationContext, actorBeanName);

Then we proceed to explain the most relevant aspects of the class:

  • SpringExtProvider is the id used to access the Spring extension.
  • The createExtension method is used internally by Akka to instantiate the extension
  • The SpringExt static class is the implementation of the extension that we are going to perform, and consists of two methods:
    • The initialize method is used to initialize the application context of Spring in the extension.
    • The props method creates a Props (the class responsible for creating the configuration of the actors) for the actor with the name of the bean passed by parameter that is in the application context that we specify in the initialize method.
      For this, it uses the SpringActorProducer class, which we will discuss next.

Next we create the class that is going to be specifically commissioned to create the actor:

SpringActorProducer.java
public class SpringActorProducer implements IndirectActorProducer {
private final ApplicationContext applicationContext;
private final String actorBeanName;
public SpringActorProducer(ApplicationContext applicationContext, String actorBeanName) {
public Actor produce() {
public Class<? extends Actor> actorClass() {
return (Class<? extends Actor>) applicationContext.getType(actorBeanName);

In order for SpringActorProducer to be able to create the actors, it needs to implement the IndirectActorProducer interface , and overwrite the two methods it has.
We observe how what it returns in the method it produces () is the Spring bean with that name, so Spring is already in charge of that actor, and we can inject dependencies from the rest of the project.

The last step necessary to communicate Spring and Akka is to make the Akka ActorSystem and the application context of Spring known. We achieve this by means of a configuration class.

AkkaConfig.java
public class AkkaConfig {
public ActorSystem actorSystem() {
ActorSystem actorSystem = ActorSystem.create(“ActorSystem”);

The @Configuration annotation serves to indicate to Spring that this class is useful when raising the context, since in this class we are able to inject the application context of Spring.
At the time of needing an ActorSystem Akka will use the one that we have created in the configuration class, and since we have not indicated anything specific its scope will be singleton type, that is, one will be created only for the whole application

5. Practical example

Once Spring and Akka are communicated, we will check how the creation of actors changes and how we are able to inject dependencies.
Next we will check how would be the case 3 of the tutorial made by Javier using Spring for us to manage the actors.

We start by defining what the general behavior of our application will be in the main () method of the Application.class class

Application.java
public class Application {
public static ActorRef espadachin;
public static ActorRef herrero;
public static ActorRef minero;
public static void main(String[] args) {
final ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
ActorSystem actorSystem = applicationContext.getBean(ActorSystem.class);
espadachin = actorSystem.actorOf(SpringExtension.SpringExtProvider.get(actorSystem).props(“espadachin”), “espadachin”);
herrero = actorSystem.actorOf(SpringExtension.SpringExtProvider.get(actorSystem).props(“herrero”), “herrero”);
minero = actorSystem.actorOf(SpringExtension.SpringExtProvider.get(actorSystem).props(“minero”), “minero”);

Let’s check the most relevant data of this class:

  • In line 10 we see the annotation @SpringBootApplication that is in charge of raising the Spring context and initializing the configuration beans (among which our actorSystem of the AkkaConfig class is included ).
  • In line 18 we obtain the ActorSystem through the application context, so we would be able to inject them in any class. We prefer to obtain it here directly so as not to complicate the example.
  • From lines 20 to 22, we declare the three actors in the example at the actorSystem level. Observe how we create the actors through the extension of Akka that we have previously created.
    The parameter that the props () method receives is the name of the bean that it is going to create, and the second parameter is the name that the bean will have in relation to the actorPath.
    I am aware that when creating the actor we could add the SpringExtension class as a static import but I preferred to leave it for reasons of clarity when reading the code.
  • Finally, once the actor is created, its use is completely normal.

Let’s check now the classes of the actors:

Espadachin.java
public class Espadachin extends UntypedActor {
public enum Mensaje {
private static final Logger log = LoggerFactory.getLogger(Espadachin.class);
public void onReceive(Object o) {
log.info(“[Espadachin] ha recibido el mensaje: \”{}\”.”, o);
if (o == Mensaje.ESPADA_ROTA) {
} else if (o == Mensaje.ESPADA_NUEVA) {
Herrero.java
public class Herrero extends UntypedActor {
public enum Mensaje {
private static final Logger log = LoggerFactory.getLogger(Herrero.class);
private final HerreroService herreroService;
public Herrero(HerreroService herreroService) {
public void preStart() {
espadachines = new ArrayList<>();
public void onReceive(Object o) throws InterruptedException {
log.info(“[Herrero] ha recibido el mensaje: \”{}\”.”, o);
if (o == Mensaje.CREAR_ESPADA) {
} else if (o == Mensaje.MATERIALES) {
log.info(“[Herrero] está creando espada…”);
log.info(“[Herrero] ha creado espada.”);
Miner.java
public class Minero extends UntypedActor {
public enum Mensaje {
private static final Logger log = LoggerFactory.getLogger(Minero.class);
private final MineroService mineroService;
public Minero(MineroService service) {
public void onReceive(Object o) throws InterruptedException {
log.info(“[Minero] has received the message: \”{}\”.”, o);
if (o == Mensaje.OBTENER_MATERIALES) {
log.info(“[Minero] is getting materials…”);
log.info(“[Minero] has obtained materials.”);

Something very important when creating actors via Spring is that you have to annotate the class with @Named and give the actor a name that is the same as the method props () .

As we can see in the classes Herrero and Minero have two services that are responsible for simulating the creation of the weapon and obtaining materials respectively. Both services are injected into the constructor via Spring.

The code of these services is:

HerreroService.java
public class HerreroService {
private static final long TIEMPO_CREACION_ESPADA = ;
public void crearEspada() throws InterruptedException {
MineroService.java
public class MineroService {
private static final long TIEMPO_OBTENCION_MATERIALES = ;
private static final Logger log = LoggerFactory.getLogger(MineroService.class);
public void obtenerMinerales() {
} catch (InterruptedException e) {

Logs are used to verify the process of creating the sword. The output when executing the applicatio.

6. Conclusions

Akka offers a simple and friendly way to add your own features thanks to the extensions system, making it easy to use Akka with Spring.

The post Integration of akka with spring: akka-java-spring appeared first on Target Veb.

This content was originally published here.