Simple feature switch using Java and Spring

Zbigniew Nitecki
2 min readJun 2, 2021

--

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 — @Configurationannotation.

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 @Beanto instantiate the HMACEncriptorbean 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.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Zbigniew Nitecki
Zbigniew Nitecki

Written by Zbigniew Nitecki

Software engineer, Kotlin enthusiast.

Responses (1)

Write a response