5分钟 springboot 整合swagger2

Posted wubenhui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5分钟 springboot 整合swagger2相关的知识,希望对你有一定的参考价值。

springboot 整合swagger2

1.maven配置文件中添加依赖

<properties>
    <swagger2.version>2.2.2</swagger2.version>
</properties>
--------------------------------------------------
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger2.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger2.version}</version>
</dependency>

2.添加SwaggerConfig.java 文件

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${server.context-path}")
    private String pathMapping;

    @Bean
    public Docket createRestApi() {
        System.out.println("https://localhost:8443" + pathMapping + "/swagger-ui.html");
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("test")
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                .pathMapping(pathMapping)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.weapp.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题")
                .description("描述")
                .termsOfServiceUrl("服务条款网址")
                .contact("justubborn")
                .version("1.0")
                .build();
    }

3.配置静态资源映射WebMvcConfig.java

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

4.在接口中使用swagger注解(参考官方文档)

@RestController
@RequestMapping
public class AppUserController {

    @Api(name=ApiConstant.GET_USER)
    @RequestMapping(value = "/api/v1/user/{id}", method = RequestMethod.GET, produces = "application/json")
    public Map<String, String> get(@PathVariable String id){
        ImmutableMap<String, String> map = ImmutableMap.of("id", id);
        return map;
    }
}

5.访问https://localhost:8443/weapp/swagger-ui.html

以上是关于5分钟 springboot 整合swagger2的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot-整合Swagger2

SpringBoot整合Swagger2

SpringBoot整合Swagger2

SpringBoot整合Swagger2

SpringBoot2 整合 Swagger2

SpringBoot整合Swagger2搭建API在线文档