Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’re going to take a look at how the Togglz library can be used with a Spring Boot application.

2. Togglz

The Togglz library provides an implementation of the Feature Toggles design pattern. This pattern refers to having a mechanism that allows determining during the runtime of an application whether a certain feature is enabled or not based on a toggle.

Disabling a feature at runtime may be useful in a variety of situations such as working on a new feature which is not yet complete, wanting to allow access to a feature only to a subset of users or running A/B testing.

In the following sections, we will create an aspect that intercepts methods with an annotation that provides a feature name, and determine whether to continue executing the methods depending on if the feature is enabled or not.

3. Maven Dependencies

Along with the Spring Boot dependencies, the Togglz library provides a Spring Boot Starter jar:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.5</version>
</parent>

<dependency>
    <groupId>org.togglz</groupId>
    <artifactId>togglz-spring-boot-starter</artifactId>
    <version>2.4.1</version>
<dependency>
    <groupId>org.togglz</groupId>
    <artifactId>togglz-spring-security</artifactId>
    <version>2.4.1</version>
</dependency>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-test</artifactId> 
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.1.214</version>
</dependency>

The latest versions of togglz-spring-boot-starter, togglz-spring-security, spring-boot-starter-web, spring-boot-starter-data-jpa, spring-boot-starter-test, h2 can be downloaded from Maven Central.

4. Togglz Configuration

The togglz-spring-boot-starter library contains auto-configuration for creating the necessary beans such as FeatureManager. The only bean we need to provide is the featureProvider bean.

First, let’s create an enumeration that implements the Feature interface and contains a list of feature names:

public enum MyFeatures implements Feature {

    @Label("Employee Management Feature")
    EMPLOYEE_MANAGEMENT_FEATURE;

    public boolean isActive() {
        return FeatureContext.getFeatureManager().isActive(this);
    }
}

The enumeration also defines a method called isActive() that verifies whether a certain feature is enabled.

Then we can define a bean of type EnumBasedFeatureProvider in a Spring Boot configuration class:

@Configuration
public class ToggleConfiguration {

    @Bean
    public FeatureProvider featureProvider() {
        return new EnumBasedFeatureProvider(MyFeatures.class);
    }
}

5. Creating the Aspect

Next, we will create an aspect that intercepts a custom AssociatedFeature annotation and checks the feature provided in the annotation parameter to determine whether it is active or not:

@Aspect
@Component
public class FeaturesAspect {

    private static final Logger LOG = Logger.getLogger(FeaturesAspect.class);

    @Around(
      "@within(featureAssociation) || @annotation(featureAssociation)"
    )
    public Object checkAspect(ProceedingJoinPoint joinPoint, 
      FeatureAssociation featureAssociation) throws Throwable {
 
        if (featureAssociation.value().isActive()) {
            return joinPoint.proceed();
        } else {
            LOG.info(
              "Feature " + featureAssociation.value().name() + " is not enabled!");
            return null;
        }
    }
}

Let’s also define the custom annotation called FeatureAssociation that will have a value() parameter of type MyFeatures enum:

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface FeatureAssociation {
    MyFeatures value();
}

If the feature is active, the aspect will continue the execution of the method; if not, it will log a message without running the method code.

6. Feature Activation

A feature in Togglz can be either active or inactive. This behavior is controlled by an enabled flag and optionally an activation strategy.

To set the enabled flag to true, we can use the @EnabledByDefault annotation on the enum value definition.

Togglz library also provides a variety of activation strategies that can be used to determine whether a feature is enabled based on a certain condition.

In our example, let’s use the SystemPropertyActivationStrategy for our EMPLOYEE_MANAGEMENT_FEATURE which evaluates the feature’s state based on the value of a System property. The required property name and value can be specified using the @ActivationParameter annotation:

public enum MyFeatures implements Feature {

    @Label("Employee Management Feature") 
    @EnabledByDefault 
    @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, 
      parameters = { 
      @ActivationParameter(
        name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME,
        value = "employee.feature"),
      @ActivationParameter(
        name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE,
        value = "true") }) 
    EMPLOYEE_MANAGEMENT_FEATURE;
    //...
}

We have set our feature to be enabled only if the employee.feature property has the value true.

Other types of activation strategies provided by the Togglz library are:

  • UsernameActivationStrategy – allows the feature to be active for a specified list of users
  • UserRoleActivationStrategy – the current user’s role is used to determine the state of a feature
  • ReleaseDateActivationStrategy – automatically activates a feature at a certain date and time
  • GradualActivationStrategy – enables a feature for a specified percentage of users
  • ScriptEngineActivationStrategy – allows the use of a custom script written in a language supported by the ScriptEngine of the JVM to determine whether a feature is active or not
  • ServerIpActivationStrategy – a feature is enabled based on IP addresses of the server

7. Testing the Aspect

7.1. Example Application

To see our aspect in action, let’s create a simple example that contains a feature for managing the employees of an organization.

As this feature will be developed, we can add methods and classes annotated with our @AssociatedFeature annotation with a value of EMPLOYEE_MANAGEMENT_FEATURE. This ensures that they will only be accessible if the feature is active.

First, let’s define an Employee entity class and repository based on Spring Data:

@Entity
public class Employee {

    @Id
    private long id;
    private double salary;
    
    // standard constructor, getters, setters
}
public interface EmployeeRepository
  extends CrudRepository<Employee, Long>{ }

Next, let’s add an EmployeeService with a method to increase an employee’s salary. We will add the @AssociatedFeature annotation to the method with a parameter of EMPLOYEE_MANAGEMENT_FEATURE:

@Service
public class SalaryService {

    @Autowired
    EmployeeRepository employeeRepository;

    @FeatureAssociation(value = MyFeatures.EMPLOYEE_MANAGEMENT_FEATURE)
    public void increaseSalary(long id) {
        Employee employee = employeeRepository.findById(id).orElse(null);
        employee.setSalary(employee.getSalary() + 
          employee.getSalary() * 0.1);
        employeeRepository.save(employee);
    }
}

The method will be called from an /increaseSalary endpoint that we will call for testing:

@Controller
public class SalaryController {

    @Autowired
    SalaryService salaryService;

    @PostMapping("/increaseSalary")
    @ResponseBody
    public void increaseSalary(@RequestParam long id) {
        salaryService.increaseSalary(id);
    }
}

7.2. JUnit Test

First, let’s add a test in which we call our POST mapping after setting the employee.feature property to false. In this case, the feature should not be active and the value of the employee’s salary should not change:

@Test
public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() 
  throws Exception {
    Employee emp = new Employee(1, 2000);
    employeeRepository.save(emp);
    
    System.setProperty("employee.feature", "false");

    mockMvc.perform(post("/increaseSalary")
      .param("id", emp.getId() + ""))
      .andExpect(status().is(200));

    emp = employeeRepository.findOne(1L);
    assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
}

Next, let’s add a test where we perform the call after setting the property to true. In this case, the value of the salary should be increased:

@Test
public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() 
  throws Exception {
    Employee emp = new Employee(1, 2000);
    employeeRepository.save(emp);
    System.setProperty("employee.feature", "true");

    mockMvc.perform(post("/increaseSalary")
      .param("id", emp.getId() + ""))
      .andExpect(status().is(200));

    emp = employeeRepository.findById(1L).orElse(null);
    assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);
}

8. Conclusions

In this tutorial, we’ve shown how we can integrate Togglz library with Spring Boot by using an aspect.

The full source code of the example can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.