Swagger2生成接口文档
参考别人的博客给线上项目做了一个swagger接口文档。
具体步骤:
因为我的项目使用的是gradle项目,所以这里以gradle项目为例:
第一步导入依赖:
compile "io.springfox:springfox-swagger2:2.9.2"
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
第二步配置类
@Configuration
@EnableSwagger2
//配置正式不使用
@Profile(value = {"test", "dev"})
public class SwaggerConfig {
@Bean
public Docket docket () {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo () {
return new ApiInfoBuilder()
.title("京东方合肥耗材供应商")
.termsOfServiceUrl("http://www.baidu.com")
.description("京东方合肥医院项目")
.version("v2.0")
.build();
}
}
配置访问静态资源:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
第三步在拦截的地方配置放行:
此处以SpringSecurity为例
在这个地方配置
重写WebSecurityConfigurerAdapter类的方法
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring(). antMatchers("/swagger-ui.html")
.antMatchers("/webjars/**")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}
我看别人是不需要在Springsecurity里面放行的,因为我之前是先在这里面放行不行才加上上面的配置的,所以具体不知道这里需不需要放行,如果需要的话可以加上:
.antMatchers("/swagger-ui.html/*","/v2/**","/swagger-resources/**").permitAll()
加在这个地方就行了
我这里主要用到的注解:
@Api:用在请求的类上,表示对类的说明
tags=“说明该类的作用,可以在UI界面上看到的注解”
value=“该参数没什么意义,在UI界面上也看到,所以不需要配置”
在swagger上的效果:
接下来是对接口的注解:
@ApiOperation:用在请求的方法上,说明方法的用途、作用
value=“说明方法的用途、作用”
notes=“方法的备注说明”
@RequestMapping(value = “/list”, method = {RequestMethod.POST})
这个注解如果不规范是POST请求或者GET请求的话展示的样子为:
@RequestMapping这个注解规范了请求如POST或者GET的话效果如下:
到此就配置完成了。