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
@EnableSwagger2
public 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.
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
@Slf4j
public 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.
You can externalize the @EnableSwagger2
to its own @Configruation
and load it conditionally via a property or profile. e.g.
@Profile("!production")
@Configuration
@EnableSwagger2
public class SwaggerConfiguration{
//Additional Swagger Beans
}
this would activate swagger for any profile that isn't production.
If you dont have Swagger annotations inside controllers... just exclude SwaggerConfig.class and swagger dependencies on build
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<excludes>
<exclude>com/company/app/SwaggerConfig.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</exclude>
<exclude>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</exclude>
</excludes>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>