1. 程式人生 > >springboot加入swagger2筆記

springboot加入swagger2筆記

boot () esp body tps -o sin cor json

參考
http://www.conglin-site.com/document/html/1494763157.html

  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. 跨域問題
http://blog.sina.com.cn/s/blog_13b4eadda0102xaam.html

加攔截器

@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筆記