在springcloud项目中使用eureka,需要服务注册中心(即下面例子中的swagger-demo-server)和服务提供者(swagger-demo-consumer),同时服务的提供者之间可以相互调用,从而实现分布式架构。
Swagger 是一个用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,能够实时同步api与文档,避免接口改动而文档未及时更新而产生的问题。
一、创建服务注册中心
file-->new-->other-->spring starterproject

选择web和eureka server构建项目,此时自动生成的pom中已添加依赖注册中心的依赖,或者是不选择,等项目生成完毕后再手动添加依赖

1.配置文件 application.properties

2.在启动类上加注解@EnableEurekaServer,表示它是一个注册中心

二、创建服务提供者
1.与注册中心的创建方式一样,此时是注意是服务端选择eureka discovery,生成的pom包括

2.在pom中添加mybati和swagger相关的依赖

3.在启动类上增加注释@EnableEurekaClient,表示提供服务
4.在配置文件application.properties配置

5.建包,结构如下

6.新建对应controller service dao dto




7.配置文件添加mybatis相关的配置

8.在启动类上添加注解@MapperScan("org.crx.swagger.dao"),扫描mapper

9.创建swagger配置类,与启动类同级

10.在controller层添加swagger配置说明

至此结束,打开swagger-ui查看效果

常用注解
在上面的代码中,使用了 @Api.@ApiOperation,下面介绍一下常用的注解
注解 描述 解释
@ApiMarks a class as a Swagger resource. 用于类对象,只有在类对象上标注该注解后,相应的api信息才能展示出来.
@ApiOperation Describes an operation or typically a HTTP method against a specific path. 描述具体的方法
@ApiImplicitParam Represents a single parameter in an API Operation. 描述具体的请求参数,比如具体的响应方法的参数为 HttpServletRequest时,我会从该参数中取一些请求参数,则可以通过该方法单独定义参数.见下面的具体说明,该参数不能单独使用,必须和@ApiImplicitParams一起使用,可参考后面的例子
@ApiImplicitParams A wrapper to allow a list of multiple ApiImplicitParam objects. 组合一组@ApiImplicitParam
@ApiParam Adds additional meta-data for operation parameters. 定义具体的请求参数,类似@RequestParam 参数,直接在方法参数上使用.
@ApiResponse Describes a possible response of an operation.返回值,该类主要有code值与message两个属性,code值必须是http 返回code值,默认会有200,404等,不能单独使用,必须和@ApiResponses一起使用
@ApiResponses A wrapper to allow a list of multiple ApiResponse objects. 组合@ApiResponse
@ApiModel Provides additional information about Swagger models. 提供对请求参数与返回结果中的model的定义
网友评论