Enable or disable Spring restful API (endpoint) based on the flag from DB

575 views Asked by At

I have a restful API which has to be enabled or disabled based on the flag value which I would be fetching during application load. But I am unable enable/disable the API using @Conditional Annotation. I can achieve this by @ConditionOnProperty by setting an property in application.properties file. But, I need a dynamic value from DB to enable/disable the API.

Condition class looks like below

@Component
public class CheckCondition implements Condition {

  @Autowired
  private AppProperties appProp;
  
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    //Get the Flag value from DB which is fetched from AppProperties
    String value = appProp.getProperty(AppPropertiesEnum.ENABLE_LOGSTASH);
    boolean flag = false;
    if(value != null && value.equalsIgnoreCase("YES"))
      flag = true;
    return flag;
  }
}
Controller class which uses CheckCondition.

@RestController
@CrossOrigin
@Conditional(CheckCondition.class)
public class CheckController {

  private static final String URL_PUT_CHECKS        = "v1/core/checks";              // PUT
  
  @Autowired
  private ContextService serviceContext;
  @Autowired
  private CheckService serviceCheck;
  
  @RequestMapping(value=URL_PUT_CHECKS, method=RequestMethod.PUT)
  public void putLogstash(@RequestBody String jsonValue) {
    serviceCheck.storeValue(request, serviceContext.getAppNameVerified(request), jsonValue);
  }
}

AppProperties is also a component in which I am making a database call to fetch flag to set the condition. While application is loaded the CheckCondition class gets initiated first and the appProp will be null. Seems it is implementing condition interface spring boot doesnot load the postProcessor methods/beans. I tried using DependsOn and Order for this. I am not sure what am I missing.

Any suggestions appreciated. Thanks in advance.

1

There are 1 answers

1
Shalika On

You can try like this way.

@RestController
public class TestController {

  @Autowired
  private CheckRepository checkRepository;

  @GetMapping("/test")
  public ResponseEntity<Object> getData() {
    boolean flag = checkRepository.findByName("value");
    if (!flag) {
      return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }

  }
}