Home > Software engineering >  Is it possible to disable one URL in controller in spring-boot?
Is it possible to disable one URL in controller in spring-boot?

Time:05-17

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

CodePudding user response:

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
}

CodePudding user response:

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.

  • Related