这个问题在这里已有答案:
我在我的春季启动项目中使用了swagger2。它运作良好,但我需要从api中排除basic-error-controller
。目前我使用正则表达式使用以下代码。它正在运作,但有任何完美的方法来做到这一点。
代码:
@Bean
public Docket demoApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex('(?!/error.*).*'))
.build()
}
在谷歌搜索后,我从GitHub,[question] How to exclude the basic-error-controller from being added to the swagger description?的一个问题中得到了解决方案。它可以使用Predicates.not()
完成。
使用Predicates.not()
后,代码如下所示。
@Bean
public Docket demoApi() {
return new Docket(DocumentationType.SWAGGER_2)//<3>
.select()//<4>
.apis(RequestHandlerSelectors.any())//<5>
.paths(Predicates.not(PathSelectors.regex("/error.*")))//<6>, regex must be in double quotes.
.build()
}
很多时间过去了,但如果有人有同样的问题,你可以通过为RestController提供选择器来做到这一点:
new Docket(SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.build();
请记住,您的控制器使用@RestController进行注释
我发现限制swagger文档显示的端点的最佳方法是:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(paths())
.build().apiInfo(metadata());
}
private Predicate<String> paths() {
return or(
regex("/firstContext.*"),
regex("/secondContext.*"));
}
private ApiInfo metadata() {
return new ApiInfoBuilder()
.title("SomeTitle")
.description("SomeDescription")
.build();
}
因此,不以swing()方法上下文开头的每个端点都不会由swagger呈现
我遇到了同样的问题。我这样做了
java
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.xxx"))
.paths(PathSelectors.any())
.build();
}
我认为你应该做的是编写一些匹配所有API端点的正则表达式,如果你正在运行微服务,那么如果你不这样做可能只是一个单词匹配那么你在问题中提出的内容可能更有意义我。
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("/accounts.*"))
.build();
}
如果您使用自定义ErrorController
只是注释它
@ApiIgnore
要么
@Api(hidden = true)
例如:
@Controller
@ApiIgnore
class MyErrorController : ErrorController {
@RequestMapping("/error")
fun handleError(request: HttpServletRequest): String {
val status: String? = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)?.toString()
val statusCode: Int? = status?.toInt()
return when (statusCode) {
HttpStatus.NOT_FOUND.value() -> return "error-404"
HttpStatus.INTERNAL_SERVER_ERROR.value() -> return "error-500"
else -> "error"
}
}
override fun getErrorPath(): String {
return "/error"
}
}
在我的情况下,当我将方法设为@Bean时,它不会显示基本错误控制器。
如果我删除@Bean,它将在swagger-ui中显示basic-error-controller。
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage(CONTROLLER_PATH))
.paths(regex("/.*")).build();}