Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Is it possible to disable an end-point

Assuming I have a controller like:

public class MyController {

  public String endpoint1() {...}

  public String endpoint2() {...}
}

I want to disable endpoint1 for whatever reason in Spring. Simply, just disable it so that it cannot be accessed. So, I am not looking for how and what response to return in that case or how to secure that endpoint. Just looking to simply disable the endpoint, something like @Disabled annotation on it or so.

SOLUTION UPDATE:

Thanks all who contributed. I decided to go with @AdolinK suggestion . However, that solution will only disable access to the controller resulting into 404 Not Found. However, if you use OpenApi, your controller and all of its models such as request/response body will still show in swagger.

So, in addition to Adolin's suggestion and also added @Hidden OpenApi annotation to my controllers like:

In application.properties, set:

cars.controller.enabled=false

Then in your controller, use it. To hide controller from the OpenApi/Swagger as well, you can use @Hiden tag:

@Hidden 
@ConditionalOnExpression("${cars.controller.enabled}")
@RestController
@RequestMapping("/cars")  
public class Carontroller {
   ...
}

After this, every end point handled by this controller will return 404 Not Found and OpenApi/Swagger will not show the controllers nor any of its related schema objects such as CarRequestModel, CarResponseModel etc.

like image 562
pixel Avatar asked Dec 06 '25 17:12

pixel


2 Answers

You can use @ConditionalOnExpression annotation.

public class MyController {

  @ConditionalOnExpression("${my.controller.enabled:false}")
  public String endpoint1() {...}

  public String endpoint2() {...}
}

In application.properties, you indicates that controller is enabled by default

my.controller.enabled=true

ConditionalOnExpression sets false your property, and doesn't allow access to end-point

like image 103
Talenel Avatar answered Dec 08 '25 19:12

Talenel


Why not remove the mapping annotation over that method?

like image 41
HARI HARAN Avatar answered Dec 08 '25 18:12

HARI HARAN