参考
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);
}
}