Swagger2 配置与应用
配置
导入pom:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.0</version>
</dependency>
springboot集成swagger2配置类:
// 用于本地环境启动swagger
@Profile("dev")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//swagger要扫描的包路径
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("后台管理系统接口文档")
.description("Swagger2后台管理系统在线文档")
// .contact(new Contact("Swagger测试","localhost:8080/rms/swagger-ui.html","xxx@163.com"))
.version("2.1")
.build();
}
}
最后访问 swagger-ui
http://localhost:8080/swagger-ui.html
若有拦截器需要放开静态资源
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private XXXInterceptor xxx;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(xxx).addPathPatterns("/xxx/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
注解
- @Api()用于类;
标识资源Controller
tags–描述controller
- @ApiOperation()用于方法;
标识接口,一个url
value="说明方法,接口"
notes="备注描述,在里面"
- @ApiParam()用于方法,参数,字段说明;
标识请求参数 - @ApiModel()用于类
标识封装类Model - @ApiModelProperty()用于方法,字段
标识封装类Model的属