1

I need to disable methods inside one controller via configs.

For example, we have two methods inside controller:

@PostMapping("hello")
public String helloFunc(@RequestBody List<String> numbers) {
        // code
}

@PostMapping("bye")
public String byeFunc(@RequestBody List<String> anotherNumbers) {
        // code
}

And we have application.yml:

controller:
    hello.enabled: true
    bye.enabled: false

So, is it possible to make it so that after these settings, one method works and the other does not? (helloFunc -> work, byeFunc -> does not work).

I tried to use an annotation @ConditionalOnProperty, but it didn't help. The function worked out anyway and responsed status 200.

Thank you

  • `@ConditionalOnProperty` is used for whether or not to create a bean during spring boot auto-configuration and put the generated bean into the application context. This annotation is used at the class level rather than at the method level which is why that would not help. For clarification, do you want the endpoints to be available? Or do you want to be able to access the endpoint but do not want the processing inside the method to happen? i.e. if i visited `http://localhost:8080/bye`, what are my expected results? 404 not found response or 200 OK with an empty response body? – krlittle May 16 '22 at 16:22
  • 1
    @krlittle the second option. I want nothing to happen at this endpoint. – Alexander Koritski May 16 '22 at 16:27

2 Answers2

0

Try this simple approach. Note that you must define a 404.html by your self.

@Value("${controller.hello.enabled}")
private String helloEnableString;

@Value("${controller.bye.enabled}")
private String byeEnableString;

@PostMapping("hello")
public String helloFunc(@RequestBody List<String> numbers) {
    if (!"true".equals(helloEnableString)) {
        return "404";   // or return a "error", it depends on your situation.
    }
    // code
}

@PostMapping("bye")
public String byeFunc(@RequestBody List<String> anotherNumbers) {
    if (!"true".equals(byeEnableString)) {
        return "404";  
    }
    // code
}
Kai-Sheng Yang
  • 1,535
  • 4
  • 15
  • 21
0

I'd recomment to put the controllers into different classes(HelloConttoller, ByeConttoler) and put ConditionalOnPropety annotation on class level. Then a bean for conttoller will not be created. Another benefit is, separation of concenrs - the entire controller class will not depend on @Value annotations for only one case.

Rauf Aghayev
  • 300
  • 1
  • 12