1. 程式人生 > >Spring集成swagger步驟

Spring集成swagger步驟

spring map try value handle mod sem pat oid

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("[email protected]",
                                 "http://www.cnblogs.com/qiang-cnblog",
                                 "[email protected]")).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步驟