{{announcement.body}}
{{announcement.title}}

Spring Boot Togglz Usage — Part Two

DZone 's Guide to

Spring Boot Togglz Usage — Part Two

In this article, we will introduce the feature flags in the properties file and control bean instantiation and initialization.

· Java Zone ·
Free Resource

Togglz is a feature flag toggle pattern library to enable or disable a feature in the application. For getting started on togglz, please refer to the introduction article.

In this article, we will discuss having the feature flags in the properties file, also on different ways feature controlling bean instantiation and initialization and feature rest API.

Prerequisites

We need spring boot project with togglz dependencies like togglz-spring-boot-starter, togglz-spring-web, togglz-spring-security. Simple date utility rest API has been created for getting the server timezone and converting the time to your timezone.

Java
 




x
23


1
    @RequestMapping(value="/timezoneconversions")
2
    public String convertTimezone(@RequestParam("timezone") String timezone) {
3
        if (!this.manager.isActive(FeatureOptions.TIMEZONECONVERSION)) {
4
            return "Feature is not active";
5
        }
6
                 System.out.println(this.manager.getFeatureState(FeatureOptions.TIMEZONECONVERSION));
7
        System.out.println(this.manager.getCurrentFeatureUser().getName());
8
        Calendar currentdate = Calendar.getInstance();
9
        DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
10
        formatter.setTimeZone(TimeZone.getTimeZone(timezone));
11
        String convertedDate = formatter.format(currentdate.getTime());
12
        formatter.setTimeZone(TimeZone.getTimeZone(timezone));
13
        return convertedDate;
14
    }
15
 
          
16
    @RequestMapping(value="/currenttimezone")
17
    public String getServerTimezone() {
18
        if (this.manager.isActive(FeatureOptions.CURRENTTZFEATURE)) {
19
            return TimeZone.getDefault().getDisplayName();
20
        } else {
21
            return "Feature not active";
22
        }
23
    }



The logic to create the current Timezone was using java SDK library and convert the time to the requested timezone using Calendar instance is quite straight-forward logic. 

Now, let's add the feature flags in the application.properties to toggle the features by creating a property for each feature( like togglz.features.<featurename>.enabled). Below properties are given for the current timezone feature and timezone conversion. It has been created with a User strategy for toggling the feature. So the suffix is added to strategy for the timezone conversion as a user and user list also given for the feature.  

Properties files
 




xxxxxxxxxx
1


1
togglz.features.CURRENTTZFEATURE.enabled=false
2
togglz.features.TIMEZONECONVERSION.enabled=true
3
togglz.features.TIMEZONECONVERSION.strategy=username
4
togglz.features.TIMEZONECONVERSION.param.users=user
5
 
          



We need to create an equivalent feature flag in the Feature implementation class.

Java
 




x


 
1
public enum FeatureOptions implements  Feature {
2
 
          
3
    @Label("Current TZ Feature")
4
    CURRENTTZFEATURE,
5
 
          
6
    @Label("Time zone conversion")
7
    TIMEZONECONVERSION,
8
    
9
    public boolean isActive() {
10
        System.out.println("greetings feature check");
11
        return FeatureContext.getFeatureManager().isActive(this);
12
    }
13
}



Then the Feature Manager injected into the class using constructor injection, with the help of Feature Manager to identify whether the feature is active or not. 

Spring-security-web protects the whole web application for authentication. (Luckily spring boot creates a dynamic password for the default user login which is displayed in server console). Feature Manager when checked for the Timezone conversion feature is active by getting the logged-in user comparing the feature user given in properties file. We need to provide the User Provider bean to the context for the togglz to verify the user toggle strategy. 

Java
 




xxxxxxxxxx
1
19


 
1
@Bean
2
    public FeatureProvider featureProvider() {
3
        return new EnumBasedFeatureProvider(FeatureOptions.class);
4
    }
5
 
          
6
    @Bean
7
    public UserProvider getUserProvider() {
8
        System.out.println("**getting the user provider");
9
 
          
10
        return new UserProvider() {
11
            @Override
12
            public FeatureUser getCurrentUser() {
13
                System.out.println("**inside the current user" +  SecurityContextHolder.getContext().getAuthentication().toString());
14
                Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
15
                String username = ((UserDetails) principal).getUsername();
16
                return new SimpleFeatureUser(username, true);
17
            }
18
        };
19
    }



In the bean factory method, the feature manager can be injected as a parameter. Then feature manager can be used to check the feature is active. 

Java
 




xxxxxxxxxx
1


 
1
@Bean
2
    public CustomerBean customerBean(FeatureManager featureManager) {
3
        if (featureManager.isActive(FeatureOptions.CUSTOMERBEANFEATURE)) {
4
            System.out.println("customer bean feature activte");
5
            return new CustomerBean(featureManager);
6
        }
7
        return null;
8
    }



Bean initialization can be controlled by the feature flag with feature manager injection and checking whether the feature is active.

Java
 




xxxxxxxxxx
1


1
    public CustomerBean(FeatureManager featureManager) {
2
        if (featureManager.isActive(FeatureOptions.CUSTOMERBEANFEATURE)) {
3
            System.out.println("customer bean feature activated");
4
        }
5
        System.out.println("customer bean created");
6
    }



The context listener "onApplicationEvent" method invoked after the togglz context setup,  In this method with the help of feature manager, checks feature is active before invoking the bean factory method ( getBean method).  

Java
 




xxxxxxxxxx
1
17


 
1
@Component
2
public class SpringTogglzListener extends TogglzApplicationContextBinderApplicationListener {
3
 
          
4
    @Autowired
5
    DefaultListableBeanFactory beanFactory;
6
 
          
7
    @Autowired
8
    ApplicationContext applicationContext;
9
 
          
10
    public void onApplicationEvent(ApplicationEvent event) {
11
        System.out.println("Wow! Togglz application context binder initialized!!!");
12
        FeatureManager featureManager = (FeatureManager) beanFactory.getBean(FeatureManager.class);
13
        System.out.println(featureManager.isActive(FeatureOptions.PRODUCTBEANFEATURE));
14
        if (featureManager.isActive(FeatureOptions.PRODUCTBEANFEATURE))
15
            System.out.println(beanFactory.getBean("productBean"));
16
    }
17
}



Here the bean factory method is annotated with Lazy annotation as shown below. So when it is requested for the first time, then only the bean will be created. 

Java
 




x


 
1
@Bean
2
@Lazy(true)
3
public ProductBean productBean() {
4
System.out.println("product bean started..");
5
return new ProductBean();
6
}



Complete source code is available in GitHub

Topics:
feature toggle, java, springbootapplication, togglz, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}