API自动生成工具

Spring Boot中使用swagger

在Spring Boot中使用swagger比较简单

添加依赖:

< dependency >
     < groupId >io.springfox</ groupId >
     < artifactId >springfox-swagger2</ artifactId >
    < version >2.7.0</ version >
</ dependency >
< dependency >
     < groupId >io.springfox</ groupId >
    < artifactId >springfox-swagger-ui</ artifactId >
    < version >2.7.0</ version >
</ dependency >


使用注解@EnableSwagger2启用Swagger:

@SpringBootApplication
@EnableSwagger2
public  class  AccountApplication {
     public  static  void  main(String[] args) {
         SpringApplication.run(AccountApplication. class , args);
     }
}


此时访问你的web服务http://localhost:8080/swagger-ui.html已经可以看到自动生成的API文档。


注意:默认情况下Swagger会自动将所有的API识别出来,如果项目中使用了Spring Cloud或其他的集成组件会自动映射很多对外接口,此时需要主动配置为哪些接口生成API文档。


配置哪些API自动生成文档

import  com.google.common.base.Predicate;
import  springfox.documentation.spi.DocumentationType;
import  springfox.documentation.spring.web.plugins.Docket;
import  static  com.google.common.base.Predicates.or;
import  static  springfox.documentation.builders.PathSelectors.regex;
……
 
@Configuration
public  class  SwaggerConfig {
     @Bean
     public  Docket swaggerSpringMvcPlugin() {
         return  new  Docket(DocumentationType.SWAGGER_2)
                 .select()
                 .paths(paths())
                 .build();
     }
     
     private  Predicate<String> paths() {
         return  or(regex( "/accounts.*" ));
     }
}

传统SpringMVC Web项目中使用Swagger

在传统SpringMVC Web项目中使用Swagger步骤与Spring Boot中基本一致

添加依赖

< dependency >
     < groupId >io.springfox</ groupId >
     < artifactId >springfox-swagger2</ artifactId >
    < version >2.7.0</ version >
</ dependency >
< dependency >
     < groupId >io.springfox</ groupId >
    < artifactId >springfox-swagger-ui</ artifactId >
    < version >2.7.0</ version >
</ dependency >


对外暴露Swagger UI访问地址

Swagger UI静态文件采用webjar的形式发布,需要手动映射静态资源路径。

< mvc:resources  mapping = "/webjars/**"  location = "classpath:/META-INF/resources/webjars/"  />


若SpringMVC匹配所有请求,还需在`web.xml`中单独映射`swagger-ui.html`路径。

< servlet-mapping >
     < servlet-name >default</ servlet-name >
     < url-pattern >/swagger-ui.html</ url-pattern >
</ servlet-mapping >


配置哪些API自动生成文档,仅需将上文中的`SwaggerConfig类`配置到Spring中。

< bean  class = "com.equals.swagger.demo.configuration. SwaggerConfig"  />




猜你喜欢

转载自blog.csdn.net/lJQueen/article/details/78622952
今日推荐