Swagger应用例子及说明

[b]Swagger应用例子及说明[/b]


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



package com.cesmart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan(basePackages = "com.cesmart") // 扫描那些包得到bean.@ComponentScan({"com.teradata.notification","com.teradata.dal"})
//@EnableSwagger2 //启动swagger注解
public class Application {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
}
}



package com.cesmart.entity;

public class TestModel {
private String name; //
private String value; //

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

@Override
public String toString() {
return "TestModel [name=" + name + ", value=" + value + "]";
}
}



package com.cesmart.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Predicates;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration//定义为spring boot 的配置文件
@EnableSwagger2//启动swagger注解
public class Swagger2 {
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.cesmart.controller";

@Bean(value="createRestApi")
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test1")
.pathMapping("/")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(Predicates.or(PathSelectors.regex("/webTest2/.*")))
.build();

//groupName,分组名字
//pathMapping,映射路径(会加到URL前面组成新的路径,如:"/xing/WebTest/webTest",(pathMapping("/xing")))
//apiInfo,API信息描述
//select, 选择那些路径和api会生成document
//apis,扫描那些包,RequestHandlerSelectors.any()表示对所有api进行监控
//paths,匹配那些路径,PathSelectors.any()表示所有路径,
}

@Bean(value="createRestApi2")
public Docket createRestApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test2")
.pathMapping("/")
.apiInfo(apiInfo2())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(Predicates.or(PathSelectors.regex("/webTest/.*")))
.build();
}


private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
.termsOfServiceUrl("http://blog.didispace2.com/")
.contact("程序猿DD")
.version("1.0")
.license("license")
.licenseUrl("licenseUrl")
.build();

//title,标题,在页面顶部显示
//description,描述,在页面顶部显示
//termsOfServiceUrl,
//contact,显示“Created by + contact”,在页面顶部显示
//version,API版本,,在页面顶部显示
//license,版权
}

private ApiInfo apiInfo2() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
.termsOfServiceUrl("http://blog.didispace2.com/")
.contact("程序猿DD")
.version("1.0")
.license("license")
.licenseUrl("licenseUrl")
.build();
}

}



package com.cesmart.controller;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cesmart.entity.TestModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(value = "WebTest", description = "有关于Swagger2操作")
@RequestMapping(value = "/webTest")
// 用在类上,说明该类的作用
// value,显示在类中的说明
// description,类中的说明
// 显示形式:“value:description”,如上面显示为"WebTest:有关于Swagger2操作"
public class WebTest {
@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
// 用在方法上,说明方法的作用
// 显示在方法说明中,显示notes
// response,接口返回参数类型
// value = "接口说明",
// notes = "接口发布说明"
@ApiImplicitParams({
@ApiImplicitParam(paramType = "path", required = true, name = "test", dataType = "String", value = "456"),
@ApiImplicitParam(paramType = "path", required = true, name = "test2", dataType = "String", value = "789") })
// @ApiImplicitParam,表示一个参数的描述,与请求参数有关系
// paramType,参数放在哪个地方
// required,参数是否必须传
// name,参数名
// dataType,参数类型(描述)
// value,参数的意思(描述)
@ApiParam
@RequestMapping(value = "/webTest/{test}/{test2}", produces = "text/plain;charset=UTF-8", method = RequestMethod.GET)
public String webTest(@PathVariable("test") String test, @PathVariable("test2") String test2) {
System.out.println("webTest");
System.out.println("test == " + test);
System.out.println("test2 == " + test2);
return "webTest";
}

@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", required = true, name = "test", dataType = "String", value = "456"),
@ApiImplicitParam(paramType = "query", required = true, name = "test2", dataType = "String", value = "789") })
@RequestMapping(value = "/webTest2", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
public String webTest2(String test, String test2) {
System.out.println("webTest");
System.out.println("test == " + test);
System.out.println("test2 == " + test2);
return "webTest";
}

@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", required = true, name = "name", dataType = "String", value = "456"),
@ApiImplicitParam(paramType = "query", required = true, name = "value", dataType = "String", value = "789") })
@RequestMapping(value = "/webTest3", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
public String webTest3(@ModelAttribute TestModel testModel) { // 这里要用@ModelAttribute,才不会出现testModel输入框
System.out.println("testModel == " + testModel.toString());
return "webTest";
}
}



package com.cesmart.controller;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cesmart.entity.TestModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(value = "WebTest", description = "有关于Swagger2操作",,tags="设备在线时长统计接口")
@RequestMapping(value = "/webTest2")
// 用在类上,说明该类的作用
// value,显示在类中的说明
// description,类中的说明
// 显示形式:“value:description”,如上面显示为"WebTest:有关于Swagger2操作"
public class WebTest2 {
@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
// 用在方法上,说明方法的作用
// 显示在方法说明中,显示notes
// response,接口返回参数类型
// value = "接口说明",
// notes = "接口发布说明"
@ApiImplicitParams({
@ApiImplicitParam(paramType = "path", required = true, name = "test", dataType = "String", value = "456"),
@ApiImplicitParam(paramType = "path", required = true, name = "test2", dataType = "String", value = "789") })
// @ApiImplicitParam,表示一个参数的描述,与请求参数有关系
// paramType,参数放在哪个地方
// required,参数是否必须传
// name,参数名
// dataType,参数类型(描述)
// value,参数的意思(描述)
@ApiParam
@RequestMapping(value = "/webTest/{test}/{test2}", produces = "text/plain;charset=UTF-8", method = RequestMethod.GET)
public String webTest(@PathVariable("test") String test, @PathVariable("test2") String test2) {
System.out.println("webTest");
System.out.println("test == " + test);
System.out.println("test2 == " + test2);
return "webTest";
}

@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", required = true, name = "test", dataType = "String", value = "456"),
@ApiImplicitParam(paramType = "query", required = true, name = "test2", dataType = "String", value = "789") })
@RequestMapping(value = "/webTest2", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
public String webTest2(String test, String test2) {
System.out.println("webTest");
System.out.println("test == " + test);
System.out.println("test2 == " + test2);
return "webTest";
}

@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", required = true, name = "name", dataType = "String", value = "456"),
@ApiImplicitParam(paramType = "query", required = true, name = "value", dataType = "String", value = "789") })
@RequestMapping(value = "/webTest3", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
public String webTest3(@ModelAttribute TestModel testModel) { // 这里要用@ModelAttribute,才不会出现testModel输入框
System.out.println("testModel == " + testModel.toString());
return "webTest";
}
}



说明:
@Api:用在类上,说明该类的作用
@ApiOperation:用在方法上,说明方法的作用
@ApiImplicitParams:用在方法上包含一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
paramType:参数放在哪个地方
header-->请求参数的获取:@RequestHeader
query-->请求参数的获取:@RequestParam
path(用于restful接口)-->请求参数的获取:@PathVariable
body(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传
value:参数的意思
defaultValue:参数的默认值
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性


本地打开:[url]http://localhost:8080/swagger-ui.html[/url]
[img]http://dl2.iteye.com/upload/attachment/0121/2849/5f92e17b-0d57-3e15-a963-21ab7c89c420.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0121/6179/462da59e-fa0d-31e4-a42b-5a3f6a65b8cd.png[/img]


[b]日期使用格式输入注解[/b]
public String getDeviceOnlineTimeByYearMonth2(String deviceType, String modelNo, String deviceId, int groupType,
@DateTimeFormat(pattern = "yyyyMMdd") Date startDate, @DateTimeFormat(pattern = "yyyyMMdd") Date endDate) {



[b]也可以在接口处使用模型的方式进行,相关参数设定放在模型中进行设置[/b]
public class ParamModel {
private Long id;
private String nameId;
@ApiModelProperty(required = true, dataType = "int", value = "1235", name = "xing")
private Integer age;
@ApiModelProperty(required = true, dataType = "date", value = "时间(yyyyMMdd)")
@ApiParam(defaultValue = "20170213")
@DateTimeFormat(pattern = "yyyyMMdd")
private Date time;
}


[b]不在接口处写@ApiImplicitParams也是会识别出来的,只不过让你对参数进行更多的处理[/b]


[b]增加公共参数[/b]
class SwaggerConfiguration {
@Bean
public Docket createRestApi() {

ParameterBuilder builder = new ParameterBuilder();
Parameter parameter = builder
.parameterType("query") //参数类型支持header, cookie, body, query etc
.name("access_token") //参数名
.description("请输入您的Access Token")
.modelRef(new ModelRef("string"))//指定参数值的类型
.required(false)
.build();
List<Parameter> parameters = Lists.newArrayList(parameter);
return new Docket(DocumentationType.SWAGGER_2)
.groupName("zlcloud-mkt-mfc-service")
.pathMapping("/")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zlcloud.mfc.controller"))
.paths(PathSelectors.any())
.build()

.globalOperationParameters(parameters);
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("[RESTful APIs]--zlcloud-mkt-mfc-service")
.description("zlcloud-mkt-mfc-service模块接口")
.contact("ZL")
.version("1.0")
.build();
}
}



[b]使用模型进行参数传递[/b]
public AjaxResult findByStatus(@RequestBody SalesParameterModel salesParameterModel) 


@ApiModel
@Table(name = "t_sell_goods")
public class Goods implements Serializable {

private static final long serialVersionUID = -8444776915480123879L;
/**
* 唯一码
*/
@Id
@ApiModelProperty(required = false, name = "goodsid", value = "唯一码",example="123456",position=1)
private Long goodsid;
}



@ApiOperation(value = "接口说明", notes = "接口发布说明", response = String.class)
@RequestMapping(value = "/test4", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST)
public String webTest4(@ApiParam(value="地址",defaultValue="123456") @RequestParam(required = true) String address) {
System.out.println("dateTimeFormatTestModel == " + address.toString());
return "test3";
}



@JsonFormat
public class DateTimeFormatTestModel2 {

@ApiModelProperty(required = false, name = "userId", value = "userId", example = "userId")
private String userId;

@ApiModelProperty(required = false, name = "date", value = "date yyyyMMdd", example = "20170809")
@JsonFormat(pattern="yyyyMMdd",timezone="GMT+8") //输入时可以用,输出时也可以用,//为了便于date类型字段的序列化和反序列化
//@DateTimeFormat(pattern = "yyyy-MM-dd") //yyyyMMdd在bean中的用是不能够进行转换的,但"yyyy-MM-dd"可以,但加了8小时
private Date date;

@ApiModelProperty(required = false, name = "name", value = "name", example = "name")
private String name;



参数为数组形式,(allowMultiple = true),参数间以","分开
allowMultiple = true, paramType = "query", dataType = "string"


@PathVariable中文乱码问题解决方式
@RequestMapping(value="/search/{key}", method = {RequestMethod.GET})  
public String searchFaceListIndex(@PathVariable(value="key") String key, Map<String, Object> result) throws UnsupportedEncodingException {
key = new String(key.getBytes("ISO-8859-1"), "utf8");
return "searchFaceList";
}


[url]https://my.oschina.net/hawt/blog/884648[/url]

@PathVariable为空时解决方式

@RequestMapping(value = {"/get/{userId}", "/get/{id}/{userId}"}, method = RequestMethod.GET)


@PathVariable(required = false) String id



参考原文(使用例子):[url]http://www.iteye.com/topic/1145103[/url]
参考原文(使用例子):[url]http://www.open-open.com/lib/view/open1455546851058.html[/url]
参考原文(定义多个组):[url]http://blog.csdn.net/catoop/article/details/50668896[/url]
参考原文(使用例子):[url]http://www.jianshu.com/p/8033ef83a8ed[/url]
参考原文(注解使用说明(英文)):[url]https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md[/url]
参考原文(注解使用说明,使用例子):[url]http://www.cnblogs.com/java-zhao/p/5348113.html[/url]
参考原文(注解使用说明(英文)):[url]https://github.com/swagger-api/swagger-core/wiki/Annotations[/url]
参考原文(官网):[url]http://swagger.io/specification/[/url]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值