Java中Swagger技术怎么用
Java中Swagger技术怎么用
这篇文章将为大家详细讲解有关Java中Swagger技术怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
Swagger的作用与概念
在前后端分离时代,我们需要实时自动更新接口信息,和测试接口,实现前后端分离式开发,swagger因此产生
在项目中使用swagger
以下以3.0.0依赖为例
<!--swagger相关组件--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>3.0.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency>
@RestControllerpublicclassHelloController{@RequestMapping(value="/hello")publicStringhello(){return"hello";}}
@Configuration@EnableSwagger2//开启swagger2publicclassSwaggerConfig{}
然后访问http://localhost:8080/swagger-ui/index.html
你就能看到如下界面,为swagger文档
配置swagger
先来看看底层的代码,了解一下
ApiInfo 配置
@Configuration@EnableSwagger2//开启swagger2publicclassSwaggerConfig{@BeanpublicDocketdocket(){returnnewDocket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());}//配置swagger信息apiInfoprivateApiInfoapiInfo(){//作者信息Contactcontact=newContact("宋先慧","https://blog.csdn.net/sxh06","xianhuisong@yeah.net");returnnewApiInfo("宋先慧的ApiDocumentation","学习swagger没有尽头","1.0","urn:tos",contact,"Apache2.0","http://www.apache.org/licenses/LICENSE-2.0",newArrayList());}}
swagger配置扫描接口
@Configuration@EnableSwagger2//开启swagger2publicclassSwaggerConfig{//@Bean//publicDocketdocket1(){//returnnewDocket(DocumentationType.SWAGGER_2).groupName("分组二");//}@BeanpublicDocketdocket(Environmentenvironment){Profilesprofiles=Profiles.of("dev");//获取项目的环境booleanflag=environment.acceptsProfiles(profiles);returnnewDocket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName("宋先慧")//分组.enable(flag)//enable配置是否启动swaggerflase则不能在浏览器访问.select()//RequestHandlerSelectors实现类配置扫描方式//basePackage指定要扫描的包//any()全部//none()都不扫描//withClassAnnotation()扫描类上的注解参数是一个注解的反射对象//withMethodAnnotation扫描方法上的注解.apis(RequestHandlerSelectors.basePackage("com.sxh.swagger.controller"))//.apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))//过滤什么路劲过滤请求//.paths(PathSelectors.ant("/sxh/**")).build();}//配置swagger信息apiInfoprivateApiInfoapiInfo(){//作者信息Contactcontact=newContact("宋先慧","https://blog.csdn.net/sxh06","xianhuisong@yeah.net");returnnewApiInfo("宋先慧的ApiDocumentation","学习swagger没有尽头","1.0","urn:tos",contact,"Apache2.0","http://www.apache.org/licenses/LICENSE-2.0",newArrayList());}}
如果我只希望在生成环境使用swagger,在正式环境不使用swagger怎么解决?(enable=false|true)
配置api文档分组
多个分组
配置多个Docket 实例即可
@BeanpublicDocketdocket1(){returnnewDocket(DocumentationType.SWAGGER_2).groupName("分组一");}@BeanpublicDocketdocket2(){returnnewDocket(DocumentationType.SWAGGER_2).groupName("分组二");}`
实体类配置
关于“Java中Swagger技术怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。