springboot项目集成swagger2

swagger2介绍

简单说明一下,Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务的接口文档。

查看生成配置文档

导入依赖包

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

增加配置类

package com.lushunde.springboot.config.swagger2;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
/**
 * @模块名:springboot
 * @包名:     com.lushunde.springboot.config.swagger2
 * @类名称:Swagger2Config
 * @类描述:在与spring boot集成时,放在与Application.java同级的目录下。
 * 			通过@Configuration注解,让Spring来加载该类配置。
 * 			再通过@EnableSwagger2注解来启用Swagger2。
 * @版本:      1.0
 * @创建人:bellus
 * @创建时间:2019年6月23日下午4:29:02
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
	
	@Value("${swagger2.configuredFlag}")
    private boolean swagger2ConfiguredFlag;
	
	/**
	 * @方法名:createRestApi
	 * @方法描述:	创建API应用
     * 				apiInfo() 增加API相关信息
     * 				通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 				本例采用指定扫描的包路径来定义指定要建立API的目录。
	 * @return
	 * @修改描述:
	 * @版本:1.0
	 * @创建人:bellus
	 * @创建时间:2019年6月23日 下午6:40:29
	 * @修改人:bellus
	 * @修改时间:2019年6月23日 下午6:40:29
	 */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) //设置信息
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lushunde.springboot.web.controller"))   //设置扫描路径
                .paths(PathSelectors.any())
                .build();
    }
    
    /**
     * 
     * @方法名:apiInfo
     * @方法描述:	创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 				访问地址:http://项目实际地址/swagger-ui.html
     * @return
     * @修改描述:
     * @版本:1.0
     * @创建人:bellus
     * @创建时间:2019年6月23日 下午6:41:06
     * @修改人:bellus
     * @修改时间:2019年6月23日 下午6:41:06
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("项目文档RESTful APIs")
                .description("Spring Boot Demo的API文档")
                .termsOfServiceUrl("https://localhiost:8081/")
                .contact(contactInfo())
                .version("1.0")
                .build();
    }
    
    /**
     * @方法名:contactInfo
     * @方法描述: 获取用户信息
     * @return
     * @修改描述:
     * @版本:1.0
     * @创建人:bellus
     * @创建时间:2019年6月22日 下午9:25:21
     * @修改人:bellus
     * @修改时间:2019年6月22日 下午9:25:21
     */
    private Contact contactInfo(){
    	return new Contact("bellus", "https://blog.lushunde.com/", "lushunde321@163.com");
    }
}

多环境切换swagger的使用开关

在生产环境下,我们需要关闭swagger配置,避免暴露接口的这种危险行为。

禁用方法1

使用注解@Profile({“dev”}) 表示在开发或测试环境开启,而在生产关闭。(推荐使用,因为本项目使用多环境与此不同,所以不适用)

禁用方法2

使用注解@ConditionalOnProperty(name = “swagger.enable”, havingValue = “true”) 然后在测试配置或者开发配置中 添加 swagger.enable = true 即可开启,生产环境不填则默认关闭Swagger.(不适用)

禁用方法3

在我们编写的swagger配置类中得开关(通过注解在不同环境配置开关)

配置类增加 .enable(swagger2ConfiguredFlag)

package com.lushunde.springboot.config.swagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {
    
	@Value("${swagger2.configuredFlag}")
    private boolean swagger2ConfiguredFlag;
	
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
        		.enable(swagger2ConfiguredFlag)
                .apiInfo(apiInfo()) //设置信息
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lushunde.springboot.web.controller"))   //设置扫描路径
                .paths(PathSelectors.any())
                .build();
    }
    
  

配置文件application.properties增加开关

swagger2.configuredFlag=true

接口注解使用demo

githubdemo:https://github.com/lushunde/springboot.git

常用注解文档

添加文档内容
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,描述的主要来源是函的命名,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。

Swagger使用的注解及其说明:

@Api:用在请求的类上,表示对类的说明常用参数:

属性说明版本
tags说明该类的作用,非空时将覆盖value的值2.9.2
value描述类的作用2.9.2
description对api资源的描述在1.5版本后不再支持
basePath基本路径可以不配置在1.5版本后不再支持
position如果配置多个Api 想改变显示的顺序位置在1.5版本后不再支持
produces设置MIME类型列表(output)例:“application/json, application/xml”,默认为空2.9.2
consumes设置MIME类型列表(input),例:“application/json, application/xml”,默认为空2.9.2
protocols设置特定协议,例:http, https, ws, wss。2.9.2
authorizations获取授权列表(安全声明),如果未设置,则返回一个空的授权值。
hidden默认为false, 配置为true 将在文档中隐藏
@RestController
@RequestMapping("/user")
@Api(tags="用户管理")
public class UserController {
	Logger logger = LoggerFactory.getLogger(UserController.class);
}

@ApiOperation:注解来给API增加方法说明。

属性说明版本
value“说明方法的用途、作用”
notes“方法的备注说明”
tags操作标签,非空时将覆盖value的值
response响应类型(即返回对象)
responseContainer声明包装的响应容器(返回对象类型)。有效值为 “List”, “Set” or “Map”。
responseReference指定对响应类型的引用。将覆盖任何指定的response()类
httpMethod指定HTTP方法,“GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”
position如果配置多个Api 想改变显示的顺序位置,在1.5版本后不再支持
nickname第三方工具唯一标识,默认为空
produces设置MIME类型列表(output),例:“application/json, application/xml”,默认为空
consumes设置MIME类型列表(input),例:“application/json, application/xml”,默认为空
protocols设置特定协议,例:http, https, ws, wss。
authorizations获取授权列表(安全声明),如果未设置,则返回一个空的授权值。
hidden默认为false, 配置为true 将在文档中隐藏
responseHeaders响应头列表
code响应的HTTP状态代码。默认 200
extensions扩展属性列表数组
@ApiOperation(value="获取用户", notes="根据用户编号查询用户后返回用户对象")

@ApiImplicitParams : 用在方法上包含一组参数说明,包含ApiImplicitParam注解。
@ApiImplicitParam:用来注解来给方法入参增加说明。

属性说明版本
name参数名,参数名称可以覆盖方法参数名称,路径参数必须与方法参数一致
value参数的汉字说明、解释
required参数是否必须传,默认为false [路径参数必填]
dataType参数类型,默认String,其它值dataType=“Integer”
defaultValue参数的默认值
paramType参数放在哪个地方 header、query、path、body、form介绍值如下
paramType值说明查询注解
header请求参数的获取@RequestHeader
query请求参数的获取@RequestParam
path(用于restful接口)请求参数的获取@PathVariable
body(不常用)
form(不常用)
    @ApiImplicitParams({
		@ApiImplicitParam(paramType="query", name = "userId", value = "用户编号", required = true, dataType = "Long")
	})

@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

属性说明版本
code数字,例如400
message信息,例如"请求参数没填好"
response抛出异常的类
	@ApiResponses({
		@ApiResponse(code=200,message="成功",response=JsonResult.class),
		@ApiResponse(code=500,message="服务器异常",response=JsonResult.class)
	})

@ApiModel:描述一个Model的信息,用在model类上
@ApiModelProperty:描述一个model的属性

属性说明版本
value此属性的简要说明。
name允许覆盖属性名称
allowableValues限制参数的可接受值。1.以逗号分隔的列表 2、范围值 3、设置最小值/最大值
access允许从API文档中过滤属性。
notes目前尚未使用。
dataType参数的数据类型。可以是类名或者参数名,会覆盖类的属性名称。
required参数是否必传,默认为false
position允许在类中对属性进行排序。默认为0
hidden允许在Swagger模型定义中隐藏该属性。
example属性的示例。
readOnly将属性设定为只读。
reference指定对相应类型定义的引用,覆盖指定的任何参数值
package com.lushunde.springboot.model;

import java.io.Serializable;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 
 * @模块名:springboot
 * @包名:     model
 * @类名称:User
 * @类描述:用户信息
 * @版本:      1.0
 * @创建人:bellus
 * @创建时间:2019年6月22日上午2:41:35
 */
@ApiModel(value="User",description="用户")
public class User implements Serializable{
	private static final long serialVersionUID = -1446919202047721900L;
	@ApiModelProperty(name="userId",value="用户编号",dataType="Long")
	private Long userId;
	@ApiModelProperty(name="username",value="用户名称",dataType="String")
	private String username;
	public Long getUserId() {
		return userId;
	}
	public void setUserId(Long userId) {
		this.userId = userId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	@Override
	public String toString() {
		return "User [userId=" + userId + ", username=" + username + "]";
	}
	
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值