码迷,mamicode.com
首页 > 编程语言 > 详细

Spring集成swagger步骤

时间:2017-10-09 15:55:57      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:包含   return   reg   sof   script   oca   ring   err   ide   

1、添加依赖,2.4.0:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.version}</version>
</dependency>
<dependency>
    <artifactId>classmate</artifactId>
    <groupId>com.fasterxml</groupId>
    <version>1.3.3</version>
</dependency>

  

2、swagger配置:

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfigure extends WebMvcConfigurerAdapter {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .genericModelSubstitutes(DeferredResult.class)
            .useDefaultResponseMessages(false)
            .forCodeGeneration(true)
            .pathMapping("")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
            .paths(PathSelectors.any())
            .build().apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("API文档").description("API文档").termsOfServiceUrl(
            "http://localhost:8080/api")
            .contact(new Contact("abc@qq.com",
                                 "http://www.cnblogs.com/qiang-cnblog",
                                 "abc@qq.com")).version("2.0").build();
    }

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

}

3、web.xml中spring servlet mapping路径必须包含/,否则不能加载某些资源,导致各种失败(Important)

<servlet>
    <servlet-name>webapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>webapp</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>webapp</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

  

4、某些资源文件可能被拦截器拦截,需过滤掉,比如:

"/swagger-resources"
"/v2/api-docs"
"/configuration/ui"

  

  

Spring集成swagger步骤

标签:包含   return   reg   sof   script   oca   ring   err   ide   

原文地址:http://www.cnblogs.com/qiang-cnblog/p/7641367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!