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"
补充:增加Header默认参数
@Bean
public Docket createRestApi() {
ParameterBuilder parameterBuilder = new ParameterBuilder();
List<Parameter> parameters = new ArrayList<Parameter>();
parameterBuilder.name("Authentication")
.description("token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false).build();
parameters.add(parameterBuilder.build());
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()
.globalOperationParameters(parameters)
.apiInfo(apiInfo());
}
效果: