How I implemented Command Pattern in Spring boot

siva ramakrishna kv
CodeX
3 min readJan 5, 2021

--

If you are familiar with Command Design Pattern you might get puzzled when you see this and start thinking about how the implementation is so different from the standard java or any other programming language. Don’t worry it’s normal to think like that. Trust me even I had the same feeling when I first started thinking about this.

The truth is fundamentally it is no different however let’s explore how we can leverage Spring’s powerful IoC(Inversion of Control) framework and simplify the command pattern implementation.

Here is a glance at the Command Design Pattern component interaction.

Source: Wikipedia

From the above diagram, we see 3 major components in this pattern

Invoker is the first one to receive a request(user interaction, web API call, etc…). The sample code can be found here.

‘Command’ is a concrete implementation of a command interface that abstracts how the user request is executed. There can be many concrete command classes for a given application. Typically the application has to gather all such commands by constructing a map and make it available for the invoker. This article focuses more on how this map can be created leveraging Spring’s IoC which removes boilerplate code.

‘Receiver’ is the one that actually performs the business logic. Receiver can be a method in a separate class or it can be part of the command class itself to keep it simple.

Two things that simplified a lot of code in Spring.

@Autowired
private Map<String, CommandInterface> commandHandlersMap;

and

@Service(CommandType.ADD_)
public class Add implements CommandInterface{

if we just annotate all the command classes with Spring’s component/service/bean annotation, spring-context will have all the information about your classes.

The best part is when we autowired the command map, as shown above, it completely blew my mind. It auto-fills the map with the command name that we provided as part of the class definition and its instance. Literally, we don’t have to manually create the map and kept on adding the command name and their instances. This clearly took away the bunch of lines of code and the linking and thus improved the readability as well.

Lastly, the downside is we are tightly coupling the business logic with the Spring framework which is not so bad IMO when we consider the benefit of this and also I guess we don’t frequently switch to other platforms that easily.

Code Sample is available here

--

--