Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic feature flag in spring

my web app has a method test which get invoked by a cronjob every two minutes, and I like to be able dynamically switching between solution a and solution b with some feature flag without deploying it each time.

@Scheduled(fixedRateService = "120000")
public void test(){
if(conditionA()) {
  // do solution A
  } else {
  // do solution B
  }
} 

I was thinking to use a cookie for this purpose but it only works on the session that I have opened, and still, the other solution could be invoked by other sessions.

is there any way that I can enforce only one solution running in production and dynamically swapping them without releasing them each time?

Update: Jonathan Johx answer is correct, and I add some clarification here

to update the value of the properties you need first to POST your key/value in x-www-form-urlencoded format to \actuator\env, then force reloading it with by post an empty payload to the \actuator\refresh

like image 599
rawData Avatar asked Oct 31 '25 16:10

rawData


1 Answers

you might use @RefreshScope annotation to refresh properties:

1.- Add @RefreshScope on class

@RefreshScope
@Component
public class Test { 

    @Value("${conditional.istrue}")
    private boolean conditional;

    @Scheduled(fixedRateService = "120000")
    public void test(){
    if(conditional) {
      // do solution A
      } else {
      // do solution B
      }
    }   
}

2.- Add flag property and allow exposure the endpoint /refresh in order to refresh new properties.

application.properties

  conditional.istrue=true
  management.endpoints.web.exposure.include=*

3.- Once the application.properties is modified for example:

  conditional.istrue=false

Then you can refresh configurations injected doing:

 curl localhost:8080/actuator/refresh -d {} -H "Content-Type: application/json"

REFERENCES - https://spring.io/guides/gs/centralized-configuration/

like image 167
Jonathan JOhx Avatar answered Nov 02 '25 06:11

Jonathan JOhx