Spring State Machine — Example Code

Arpit Jain
Calvin Codes
Published in
2 min readJan 14, 2017

Hi All!

I am experimenting with spring state machine module these days for one of my projects. While the official documentation of Spring State Machine is very detailed and well articulated, I faced some issues while starting up the example code provided in their documentation. This article is a bit more detailed version of the same example code provided in spring docs.

I assume you have already gone through the introduction to Spring State Machine, which is a pre-requisite of this article.

So, let’s start off, by creating the main application class from where we will be running the spring application and providing execution commands to our state machine bean.

The above class is the main application code. One of the common mistakes while creating this class is to put it in the default package (under root, without any sub-package). In such a case, you will get the following warning upon starting your application:

** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.

If you are facing similar issue, I suggest reading this article about Structuring your code while using spring boot. In short, the problem here is that @ComponentScan is going to scan every class from every jar, for being placed in the default package at the root. Thus your application may try to wire unwanted beans whose dependencies are not even provided in the application context.

To overcome the same, you may follow this simple structure for your project.

com 
+- state-machine-core
| +- app
| +- Application.java
| |
| +- StateMachineConfig.java
|
+- state-machine-domain
+- enums
+- States.java
+- Events.java

Next, StateMachineConfig.java, States.java and Events.java classes can be replicated exactly how told in the example code in spring docs.

A small change which I did to my StateMachineListener bean was to capture the state machine initialisation event as well. To do that, you just need to add an extra if-else block in the overridden stateChanged method as below.

Now to start up your state machine, you just need to build your project (I am a maven user) using

mvn clean package

and run the same using

java -jar target/spring-state-machine-0.1.0.jar

Note: Replace spring-state-machine with the artifactid of your project.

I hope you find this article helpful. You may find the source code of above here.

--

--

Arpit Jain
Calvin Codes

Scalability & Big Data Enthusiast | Microsoft | Sumo Logic | UW Madison | Myntra | IIT Guwahati