`
huangyongxing310
  • 浏览: 490347 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

Swagger应用例子及说明

阅读更多
Swagger应用例子及说明


<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的属性


本地打开:http://localhost:8080/swagger-ui.html





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



也可以在接口处使用模型的方式进行,相关参数设定放在模型中进行设置
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;
}


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


增加公共参数
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();
    }
}




使用模型进行参数传递
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";  
} 


https://my.oschina.net/hawt/blog/884648

@PathVariable为空时解决方式

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


@PathVariable(required = false) String id






参考原文(使用例子):http://www.iteye.com/topic/1145103
参考原文(使用例子):http://www.open-open.com/lib/view/open1455546851058.html
参考原文(定义多个组):http://blog.csdn.net/catoop/article/details/50668896
参考原文(使用例子):http://www.jianshu.com/p/8033ef83a8ed
参考原文(注解使用说明(英文)):https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md
参考原文(注解使用说明,使用例子):http://www.cnblogs.com/java-zhao/p/5348113.html
参考原文(注解使用说明(英文)):https://github.com/swagger-api/swagger-core/wiki/Annotations
参考原文(官网):http://swagger.io/specification/
  • 大小: 46.7 KB
  • 大小: 34.2 KB
分享到:
评论

相关推荐

    springboot整合swagger2实例

    SpringBoot整合Swagger2实例详解 在现代Web开发中,API文档的重要性不言而喻,它为开发者提供了清晰的接口说明,使得开发、测试和维护工作更加高效。Swagger2是一款流行的API文档工具,它能自动生成RESTful API的...

    springboot+mybatis+swagger2实例

    【标题】"springboot+mybatis+swagger2实例"是一个集成应用,展示了如何在Spring Boot项目中结合MyBatis和Swagger2来实现数据库查询及API文档的自动化生成。在这个实例中,开发人员可以利用Spring Boot的快速开发...

    swagger @ApiModel 返回内容注释不显示问题

    1. **Swagger配置问题**:首先,确保在SpringBoot应用中正确配置了Swagger。通常,你需要在主配置类或者一个专门的配置类中添加`@EnableSwagger2`注解,然后创建一个`Docket`实例,通过`apiInfo`方法来设置API的基本...

    EasyExcel+swagger+sqltoy例子.zip

    同时,`Swagger2`可以用来定义和暴露这些操作的API,形成清晰的接口说明。 综上所述,`EasyExcel`、`Swagger2`和`SqlToy`是Java开发中的三个强大工具,它们分别解决了Excel处理、API文档生成和数据库操作的问题。在...

    自己写的一个简单的swagger小项目

    例如,我们可以引入`Docket`类来创建一个Swagger配置实例,并配置Swagger的属性,如API的分组、版本、基本路径等。 最后,为了使Swagger UI能够工作,我们需要在应用的web入口(通常是`index.html`或`swagger-ui....

    springboot集成swagger实现接口管理源码

    此外,Swagger还支持与其他工具的集成,比如Swagger Codegen,可以生成客户端SDK,使得其他语言的应用也能轻松调用你的API。这进一步提升了API的可复用性和便捷性。 总之,SpringBoot集成Swagger是一种高效、直观的...

    springboot整合swagger构建Api文档

    使用`@EnableSwagger2`注解开启Swagger支持,然后定义`Docket`实例,设置API的信息。 在业务代码中,我们需要使用Swagger的注解来描述我们的RESTful接口。例如,用`@Api`注解在Controller类上,表示这是一个包含一...

    springboot-swagger2-demo.rar

    2. **配置Swagger2**:在SpringBoot的配置类中,我们需要创建一个`Docket`实例来配置Swagger。这通常包括指定API的基本信息(如版本、描述)以及扫描哪些包中的接口。 ```java @Configuration @EnableSwagger2WebMvc...

    09_swagger文档和整合zuul.rar

    它为微服务架构提供了统一的入口,将请求路由到相应的服务实例,并且可以添加各种过滤器进行权限验证、日志记录等操作。将Swagger与Zuul整合,意味着我们可以在Zuul网关上直接查看和测试API,无需直接访问各个微服务...

    swagger2Test.rar

    3. **定义 Swagger2 配置**:在同一个配置类中,创建一个 `Docket` 实例,用来定义 API 文档的基本信息,如 API 的版本、描述、主机地址等。例如: ```java @Bean public Docket createRestApi() { return new ...

    springBoog和Swagger2使用的接口注解

    Spring Boot结合Swagger2为开发者提供了一种简便高效的方式来创建、维护及展示RESTful API文档。本文将详细介绍一系列关键的接口注解及其应用场景,帮助读者更好地理解和运用这些注解来构建高质量的API。 #### 二、...

    swagger ui 的官方库

    Swagger UI 是一个强大的工具,用于展示和交互API(应用程序编程接口)。它基于开源的Swagger规范,使得开发者可以轻松地创建、文档化并测试RESTful API。Swagger UI的官方库提供了完整的解决方案,帮助开发者构建...

    Spring Boot 整合Swagger实现API管理-教案.pdf

    Swagger通过注解的方式,为Spring Boot应用中的API增加了文档自动生成的能力。下面将详细解释Swagger中常用的注解: 1. @Api:标注在类上,用于描述这个类的作用。 2. @ApiOperation:标注在方法上,用于为API增加...

    swagger接口设计.docx

    启动应用后,访问`http://localhost:8080/swagger-ui.html`(根据你的应用端口和配置),你将看到Swagger UI,这里可以浏览和测试你的API接口。 总的来说,Swagger接口设计涉及导入必要的依赖,配置扫描范围,以及...

    swagger-ui-generator:该存储库使用swagger-jsdoc库将用jsdoc编写的端点文档转换为您定义的路径中的swagger文件

    Swagger UI是Swagger生态中的一个重要部分,它是一个Web应用程序,可以动态渲染OpenAPI规范描述的API,提供交互式的文档界面。通过Swagger UI,开发者和最终用户能够查看API的定义,尝试不同的操作,查看响应,无需...

    Springboot集成Swagger详解经过

    在本文中,我们将深入探讨如何在Spring Boot应用中集成Swagger,并详细解析集成过程及关键配置。Swagger是一款强大的API文档工具,它可以自动生成RESTful API的文档,帮助开发者更轻松地管理和测试API。以下是对...

    如何集成swagger2构建Restful API

    最后,当我们运行应用并访问Swagger UI的URL(通常是`/swagger-ui.html`),就可以看到生成的RESTful API文档了。用户可以通过这个界面查看API的详细信息,包括端点、请求方法、参数和返回类型,甚至可以直接测试API...

    swagger-ui-test

    这个名为"swagger-ui-test"的项目很可能是用来演示或测试Swagger UI功能的实例。在深入讨论相关知识点之前,我们先来理解一下Swagger和Swagger UI的核心概念。 Swagger是一种规范和完整的框架,用于设计、构建、...

    AppInfoSystem

    本项目“AppInfoSystem”显然围绕Swagger展开,旨在提供一个关于Swagger配置的实例,帮助开发者更好地理解和应用Swagger。 Swagger通过使用OpenAPI Specification(OAS,以前称为Swagger Specification)来定义和...

    springboot+dubbo+redis+RabbitMQ 项目实例

    在本项目实例中,我们探讨的是如何整合SpringBoot、Dubbo、Redis以及RabbitMQ来构建一个高效、可扩展的Java应用程序。以下是对这些技术及其整合的详细解释: 1. **SpringBoot**: SpringBoot是由Pivotal团队提供的...

Global site tag (gtag.js) - Google Analytics