Temporal Activities as Spring Beans (an Addendum)

This is a quick little addendum to last week’s post on Spring and Temporal.

In last week’s post I covered a range of different ways to use the Spring Framework with Temporal that included leveraging abstractions for making HTTP calls, and using the Spring Boot Maven plugin to build fat jars. But the topic that offered the most uncertainty (when I started the exercise) was making the Temporal worker a Spring Boot application, and allowing various portions of the implementation to be Spring beans. I concluded that workflows should NOT be Spring beans, but that the main worker application and activities COULD be Spring beans.

But the implementation that I offered, and drew a diagram for, only made the worker a bean, not the activities, and while this was fine, it was a bit awkward. The awkwardness comes from the fact that I injected configuration into the worker, specifically into the PostAggregatorWorkerConfig, only to pass it over to the activity via the constructor.

Injecting the property values directly into the activities implementation would be more elegant, after all, that is where they are used. To use Spring to inject that configuration, however, meant that I’d need to make the Activities implementation class a Spring Bean. As I said, I had reached the conclusion that this worked, so I made changes in two places:

First, in the PostAggregatorActivitiesImpl class we do two things:

  1. By adding the @Component annotation to the PostAggregatorActivitiesImpl class, Spring will now create an instance of this class; that is, it creates a Spring bean.
  2. And because Spring is managing the instance, property values can now be injected into the instance via @Value annotations.

Then, in the PostAggregatorWorkerConfig we do two things:

  1. We add a PostAggregatorActivitiesImpl parameter into the method that creates the worker bean. Spring will auto-wire the bean it created as a result of the @Component annotation.
  2. And then we register that Activity implementation instance with the worker that is created. Note that in the original implementation, WE were lifecycle managing the Activities instance — we called new when registering the Activities implementation. Now Spring is lifecycle managing it for us.

Here’s an updated diagram:

I like this new approach better and you’ll find that implementation here.

As always, would love to hear from you if you found something helpful, and/or have suggestions for improvement.

This has been cross posted on Medium as well

Share Your Thoughts