海码充电站的技术专栏 java Coder

swagger

2018-11-30
watermelon


前言

用到一个swagger,通过配置、注解,为每个接口生成接口说明和测试支持。省了程序员写文档的时间,有更多时间陪女朋友了~ 围观springboot整合swagger2

1:pom依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>

2:代码配置swagger2

/**
 * Swagger2配置类
 * 在与spring boot集成时,放在与Application.java同级的目录下。
 * 通过@Configuration注解,让Spring来加载该类配置。
 * 再通过@EnableSwagger2注解来启用Swagger2。
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.bianla.bianlaWeb.bianlaWeb.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("https://bookmanxy.github.io/)
                .termsOfServiceUrl("https://bookmanxy.github.io/")
                .contact("sunf")
                .version("1.0")
                .build();
    }
}

3:controller使用

@Api(tags ="接口名字")
public class MyController {
    @ApiOperation(value="方法描述",nickname="昵称吧,不知道显示在哪")
    public Result myMethod(String param......){
        ···
    }
}

更多配置:

问题

1:如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。需要重新制定静态资源

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

Comments

Content