Spring Boot and Togglz Aspect – Spring Boot和Togglz Aspect

最后修改: 2017年 5月 2日

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.

在本教程中,我们将看看如何将Togglz库用于Spring Boot应用程序。

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.

Togglz提供了Feature Toggles设计模式的一个实现。该模式指的是拥有一种机制,允许在应用程序的运行期间根据切换来确定是否启用某个功能。

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:

除了Spring Boot的依赖,Togglz库还提供了一个Spring Boot Starter jar。



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")

    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:

然后我们可以在Spring Boot配置类中定义一个EnumBasedFeatureProvider类型的bean。

public class ToggleConfiguration {

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

5. Creating the Aspect

5.创建 “前景”

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:


public class FeaturesAspect {

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

      "@within(featureAssociation) || @annotation(featureAssociation)"
    public Object checkAspect(ProceedingJoinPoint joinPoint, 
      FeatureAssociation featureAssociation) throws Throwable {
        if (featureAssociation.value().isActive()) {
            return joinPoint.proceed();
        } else {
              "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:


@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:

在我们的示例中,让我们为我们的 EMPLOYEE_MANAGEMENT_FEATURE 使用 SystemPropertyActivationStrategy ,它根据一个 System 属性的值来评估该功能的状态。可以使用@ActivationParameter注释来指定所需的属性名称和值。

public enum MyFeatures implements Feature {

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

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:

首先,让我们定义一个Employee实体类和基于Spring Data的资源库。

public class Employee {

    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:


public class SalaryService {

    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);

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


public class SalaryController {

    SalaryService salaryService;

    public void increaseSalary(@RequestParam long 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:


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

      .param("id", emp.getId() + ""))

    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:


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

      .param("id", emp.getId() + ""))

    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.

在本教程中,我们展示了如何通过使用一个方面将Togglz库与Spring Boot集成。

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