How to fully disable swagger-ui in spring-boot?(/swagger-ui.html should return 404) How to fully disable swagger-ui in spring-boot?(/swagger-ui.html should return 404) spring spring

How to fully disable swagger-ui in spring-boot?(/swagger-ui.html should return 404)


My answer is similar to the answer provided earlier with a slight difference. I usually create a separate spring profile named swagger. When I want to enable Swagger, l pass the following VM flag while starting my application, -Dspring.profiles.active=swagger. Here is an example of my Swagger configuration,

@Profile(value = {"swagger"})@Configuration@EnableSwagger2public class SwaggerConfiguration {    ...}

Next time when you try to access swagger-ui.html without swagger profile, you will get an empty Swagger screen but not 404.

enter image description here

If you don't want to load the static Swagger UI page at all, you can write a simple controller as shown below,

@Profile("!swagger")@RestController@Slf4jpublic class DisableSwaggerUiController {    @RequestMapping(value = "swagger-ui.html", method = RequestMethod.GET)    public void getSwagger(HttpServletResponse httpResponse) throws IOException {        httpResponse.setStatus(HttpStatus.NOT_FOUND.value());    }}

Now if you try to access swagger-ui.html without swagger profile, you will get a 404.


with swagger 3.0.0 version you can add springfox.documentation.enabled=false in corresponding environment profile application.properties file.For example, I have added this to application-prod.properties to disable in production (while running the app you must specify the profile using VM args like -Dspring.profiles.active=prod)


You can externalize the @EnableSwagger2 to its own @Configruation and load it conditionally via a property or profile. e.g.

@Profile("!production")@Configuration@EnableSwagger2public class SwaggerConfiguration{    //Additional Swagger Beans

}

this would activate swagger for any profile that isn't production.