SpringBoot/Swagger,在Swagger上只显示特定的控制器?

1l5u6lss  于 2023-08-05  发布在  Spring
关注(0)|答案(2)|浏览(190)
  • Spring Boot :2.1.3.RELEASE
  • Java 8
  • Springfox-swagger2:2.9.2

SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public static final String AUTHORIZATION_HEADER = "Authorization";

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).paths(PathSelectors.any()).
                        build().apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("API").description("DEMO").version("v1").build();
    }

    private ApiKey apiKey() {
        return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
    }
}

字符串
这个配置显示了所有的控制器,如何在Swagger上只显示特定的控制器?

xa9qqrwz

xa9qqrwz1#

1.同一包内的具体控制器

@Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.tm.x.y.z.your.controller")).paths(PathSelectors.any()).
                        build().apiInfo(apiInfo());
    }

字符串
显示软件包com.tm.x.y.z.中的所有Controller。您的.controller

2.不同包中的具体Controller

  • 创建类注解(例如:ShowAPI注解)
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface ShowAPI {
    String value() default "";
}

  • 向控制器添加注解
@RestController
 @ShowAPI
 public class ExampleController {
 }

  • 更改swagger配置
@Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).select()
                    .apis(RequestHandlerSelectors.withClassAnnotation(ShowAPI.class)).paths(PathSelectors.any()).build()
                    .apiInfo(apiInfo());
        }


Show all controller with class annotation is ShowAPI

ndh0cuux

ndh0cuux2#

使用**@ApiIgnore**标注即可。
1-忽略控制器类

@ApiIgnore 
@RestController
public class HelloController {
.....
.....
}

字符串
2-忽略特定方法

@RestController
public class HelloController {
    
    @ApiIgnore 
    @RequestMapping(method = RequestMethod.GET, value = "/api/testmethod")
    public String sayHello() {
        return "Swagger Hello World";
    }
}

相关问题