本篇文章给大家分享的是有关SpringBoot中怎么使用swagger2构建Restful APIs,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
第一步,引入对应jar包:
<!-- 集成swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.0</version>
</dependency>
第二步,基本信息配置:
@Configuration
@EnableSwagger2
public class Swagger2Config {
/**
* 在这个配置类里面我么实例化了一个Docket对象,这个对象主要包括三个方面的信息:
--整个API的描述信息,即ApiInfo对象包括的信息,这部分信息会在页面上展示。
--指定生成API文档的包名。
--指定生成API的路径。按路径生成API可支持四种模式,这个可以参考其源码:
* */
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zzw.bootlaunch.rest"))
.paths(PathSelectors.regex("/rest/.*"))
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("XXX系统的API")
.description("这是一个XXX系统的描述")
.termsOfServiceUrl("http://127.0.0.1:8080")
.contact("zhangsanfeng")
.version("V1.0")
.build();
}
}
基础的配置是对整个API文档的描述以及一些全局性的配置,对所有接口起作用。这里涉及到两个注解:
@Configuration是表示这是一个配置类,是JDK自带的注解,前面的文章中也已做过说明。
@EnableSwagger2的作用是启用Swagger2相关功能。
在这个配置类里面我么实例化了一个Docket对象,这个对象主要包括三个方面的信息:
整个API的描述信息,即ApiInfo对象包括的信息,这部分信息会在页面上展示。
指定生成API文档的包名。
指定生成API的路径。按路径生成API可支持四种模式,这个可以参考其源码:
public class PathSelectors {
private PathSelectors() {
throw new UnsupportedOperationException();
}
public static Predicate<String> any() {
return Predicates.alwaysTrue();
}
public static Predicate<String> none() {
return Predicates.alwaysFalse();
}
public static Predicate<String> regex(final String pathRegex) {
return new Predicate<String>() {
public boolean apply(String input) {
return input.matches(pathRegex);
}
};
}
public static Predicate<String> ant(final String antPattern) {
return new Predicate<String>() {
public boolean apply(String input) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(antPattern, input);
}
};
}
}
从源码可以看出,Swagger总共支持任何路径都生成、任何路径都不生成以及正则匹配和ant 模式匹配四种方式。大家可能比较熟悉的是前三种,最后一种ant匹配,如果不熟悉ant的话就直接忽略吧,前三种应该足够大家在日常工作中使用了。
按照rest风格编写服务类
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleRestController {
@Resource
ArticleRestService articleRestService;
/**
* 保存
* */
@RequestMapping(value="/article", method = RequestMethod.POST, produces = "application/json")
public AjaxResponse saveArticle(@RequestBody Article article){
log.info("saveArticle:{}",article);
//操作数据库
articleRestService.saveArticle(article);
return AjaxResponse.sucess(article);
}
/**
* 删除
* */
@RequestMapping(value="/article/{id}", method = RequestMethod.DELETE, produces = "application/json")
public AjaxResponse delArticle(@PathVariable Long id){
log.info("delArticle:{}", id);
//操作数据库
articleRestService.deleteArticle(id);
return AjaxResponse.sucess(id);
}
/**
* 更新
* */
@RequestMapping(value="/article/{id}", method = RequestMethod.PUT, produces = "application/json")
public AjaxResponse updateArtice(@PathVariable Long id, @RequestBody Article article){
log.info("updateArtice:{}",article);
//操作数据库
article.setId(id);
articleRestService.updateArticle(article);
return AjaxResponse.sucess(article);
}
/**
* 获取单条记录
* */
@RequestMapping(value = "/article/{id}", method = RequestMethod.GET, produces = "application/json")
public AjaxResponse getArtice(@PathVariable Long id){
/*Article article = Article.builder().id(22L).author("张三").content("我是内容内容....")
.title("我是标题标题...").createTime(new Date()).build();
log.info("getArtice:{}", article);*/
//操作数据库
Article article = articleRestService.getArticle(id);
return AjaxResponse.sucess(article);
}
第三步,启动并访问
启动Spring boot,然后访问:http://127.0.0.1:8080/swagger-ui.html 即可看到如下结果:
我们还可以点进去看一下每一个具体的接口,我们这里以“POST /rest/article”这个接口为例:
可以看到,Swagger为每一个接口都生成了返回结果和请求参数的示例,并且能直接通过下面的"try it out"进行接口访问,方面大家对接口进行测试。整体上感觉Swagger还是很强大的,配置也比较简单。
不过大家看到这里肯定会有点疑问:
第一个问题:这个返回结果和请求参数都没有中文文字性的描述,这个可不可以配置?
第二个问题:这个请求参应该是直接根据对象反射出来的结果,但是不是对象的每个属性都是必传的,另外参数的值也不一定满足我们的需求,这个能否配置?
答案肯定是可以的,现在我们就来解决这两个问题,直接看配置的代码:
列表页:
可以看到,现在接口都位于Article这个tag下,并且接口后面也有了我们配置好的说明。我们再看下”POST /rest/article“这个接口的详情页:
如果我们的请求参数是一个对象,那如何配置呢?这就涉及到另外两个注解:@ApiModel和@ApiModelProperty,我们还是先看代码,然后再解释,这样更容易理解:
@ApiModel(value="article对象",description="新增&更新文章对象说明")
public class Article {
@Id
@GeneratedValue
@ApiModelProperty(name = "id",value = "文章ID",required = false,example = "1")
private Long id;
@ApiModelProperty(name = "title",value = "文章标题",required = true,example = "测试文章标题")
private String title;
@ApiModelProperty(name = "summary",value = "文章摘要",required = true,example = "测试文章摘要")
private String summary;
@ApiModelProperty(hidden = true)
private Date createTime;
@ApiModelProperty(hidden = true)
private Date publicTime;
@ApiModelProperty(hidden = true)
private Date updateTime;
@ApiModelProperty(hidden = true)
private Long userId;
@ApiModelProperty(name = "status",value = "文章发布状态",required = true,example = "1")
private Integer status;
@ApiModelProperty(name = "type",value = "文章分类",required = true,example = "1")
private Integer type;
}
@ApiModel是对整个类的属性的配置:
value:类的说明
description:详细描述
@ApiModelProperty是对具体每个字段的属性配置:
name:字段名称
value:字段的说明
required:是否必须
example:示例值
hidden:是否显示
完成上面的配置后,我们再来看效果:
点击Try it out后,我们就可以看到返回的结果:
操作还是很方便的,相比Junit和postman,通过Swagger来测试会更加便捷,当然,Swagger的测试并不能代替单元测试,不过,在联调的时候还是有非常大的作用的。
以上就是SpringBoot中怎么使用swagger2构建Restful APIs,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/zhang2xiang/blog/3100491