Manonandan S K
Manonandan S K

Reputation: 652

How to disable a method in java @component class?

I am using java 8 with spring boot
I have a class

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
class Sample{
    @Scheduled(cron = "00 00 00 * * *")
    public void print(){
        System.out.println("Hello World!");
    }
}

This method is will be invoked daily at 00:00:000 AM
Now for a time beeing I want to stop invoking that method.
One way we can comment the method.
Is there any better way to do that?
Like @Disabled in junit.

Upvotes: 1

Views: 2086

Answers (3)

The Rocket
The Rocket

Reputation: 81

I agree on the approaches mentioned above but there is an another alternative as well like the below,

To implement a Spring "condition" interface which overrides the matches method with a return type of boolean value (i.e., You can write your own custom logic with boolean return).

then, use the Annotation @Conditional(yourconditionclassname.class) on the @Component/@Configuration/@bean. This way, the scheduled method executes only when the condition class returns true.

Hope this helps as an alternative approach.

Upvotes: 0

Himanshu
Himanshu

Reputation: 164

You can to use application.yml for feature flags in Spring Boot apps. This file usually defines the configuration of an application and simultaneously can be a perfect place for feature toggle. Based on a flag you can enable/disable the funcionality.

feature-flags:
    is-xyz-method-enabled :true

inside the method just simply do a check for this property.

  @Value("${is-xyz-method-enabled}")
  private boolean isEnabled;

  @Scheduled()
  public void xyz() {
    if(isEnabled) {
 
    }
  }

    

Upvotes: 1

shockwave
shockwave

Reputation: 450

Add condition on component like

@ConditionalOnProperty(name="schdularEnabled", value="true")

Then you can use application.yml with environment variables to toggle the shchedular

Upvotes: 5

Related Questions