Simple feature switch using Java and Spring

Feature switch (known also as feature toggle) is a robust approach allowing introduction of new application behaviour without changing the existing code. As the feature switch can emerge as a pretty complex solution, and have various usages, one might consider multiple approaches to the topic.
But what when we need just a simple, clean solution having Spring in our project libraries?
Spring is a powerful framework, featuring a ton of modules and provides the functionality to reduce boilerplate. But today we will be looking at Spring’s bread and butter — @Configuration
annotation.
Let’s say that we have a simple class containing one (or more) public method:
The calculateHmac()
method has an implementation that we have been using for some time. However, because of new requirements required in the upcoming change request (in my case it was the migration of various applications from Mule 3 to Mule 4). Now is the time to introduce an interface:
Now we have to implement HMACEncriptor
in ourHashingHMACEncryptor
class:
The time has come to introduce a new implementation of HMACEncryptor
:
We have two implementations of HMACEncryptor
class. We can create the bedrock of our feature switch:
We are using three Spring annotations here. @Value
is used to read values from application.properties
file. @Configuration
has a variety of uses, but in our case it is used coupled with @Bean
to instantiate the HMACEncriptor
bean at the creation time in spring bean lifecycle.
As You can see, the bean creation method is using the if-else
syntax to return either DataWeaveHMACEncriptor
or HashingHMACEncriptor
basing on the entry use.dataweave.hmac
in application.properties
, so the last thing to do is to add this entry to the configuration file:
The application behaviour can be modified by changing this entry to true
or false
, depending on which HMACEncryptor
implementation we want to use.