javaspringspring-bootfeaturetoggle

Feature-Toggle for Spring components


I have a Spring Boot application with a lot of @Component, @Controller, @RestController annotated components. There are about 20 different features which I would like to toggle separatly. It is important that features can be toggled without rebuilding the project (a restart would be ok). I think Spring configuration would be a nice way.

I could image a config (yml) like this:

myApplication:
  features:
    feature1: true
    feature2: false
    featureX: ...

The main problem is that I don't want to use if-blocks in all places. I would prefer to disable the components completely. For example a @RestController should even be loaded and it should not register its pathes. I'm currently searching for something like this:

@Component
@EnabledIf("myApplication.features.feature1")  // <- something like this
public class Feature1{
   // ...
}

Is there a feature like this? Is there an easy way to implement it myself? Or is there another best practice for feature toggles?

Btw: Spring Boot Version: 1.3.4


Solution

  • You could use @ConditionalOnProperty annotation:

    @Component
    @ConditionalOnProperty(prefix = "myApplication.features", name = "feature1")
    public class Feature1{
       // ...
    }