springboot+swagger2笔记

Posted homer3000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot+swagger2笔记相关的知识,希望对你有一定的参考价值。

参考
 
1. pom
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.13</version>
</dependency>
 
2. 与springboot集成
@Configuration
@EnableSwagger2
public class Swagger2 {
 
@Bean
public Docket config() {
return new Docket(DocumentationType.SWAGGER_2)
.host("127.0.0.1:8080")
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("cc.homer3000.web"))
.build();
}
 
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Blog系统API文档")
.contact(new Contact("作者", "访问地址", "联系方式"))
.build();
}
}
 
3. 下载swagger ui
https://github.com/swagger-api/swagger-ui
dist 目录 index.html
url: "http://petstore.swagger.io/v2/swagger.json"
修改为: url: "http://127.0.0.1:8080/v2/api-docs",
 
4. 跨域问题
 
加拦截器
@Component
public class CORSInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 添加跨域CORS
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
return true;
}
}
 
@Configuration
public class CrossDomain extends WebMvcConfigurerAdapter {
@Autowired
private CORSInterceptor corsInterceptor;
 
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(corsInterceptor);
}
}
 

以上是关于springboot+swagger2笔记的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot学习笔记:集成swagger2

SpringBoot整合Swagger2

SpringBoot-整合Swagger2

SpringBoot框架 之 Swagger2

SpringBoot集成Swagger2在线文档

SpringBoot整合Swagger2搭建API在线文档