DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements

Trending

  • Start Coding With Google Cloud Workstations
  • The Role of Functional Programming in Modern Software Development
  • Testing SingleStore's MCP Server
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot Togglz Usage — Part Two

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.

By 
Nagappan Subramanian user avatar
Nagappan Subramanian
DZone Core CORE ·
Sep. 08, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
6.1K Views

Join the DZone community and get the full member experience.

Join For Free

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. 

Spring Framework Spring Boot feature flag Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!