springboot 集成 swagger2

springboot 集成 swagger2,配置类

具体步骤:
1,引入 jar 包

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

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

2,编写 configuration 类

package com.xxx.common.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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;

/**
 * Swagger2配置
 * eg: http://localhost:8090/swagger-ui.html
 * @date 2018/5/3 10:52
 * @since
 * @param
 */
@Configuration
// @ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true")  // 是否启用该 config
// @Profile{"dev, local"}
@EnableSwagger2
public class Swagger2Configuration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())  // 基本信息
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.test.controller"))  // 指定扫描的包
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxx系统-xxx服务 RESTful APIs")
                .description("xxx服务后台api接口文档")
                .contact(new Contact("xxx", null, "[email protected]"))
                .version("1.0")
                .build();
    }
}

3,常用的注解介绍与使用

3.1,swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

@Api()  用于类;表示标识这个类是swagger的资源 
	tags–表示说明 
	value–也是说明,可以使用tags替代 
@ApiOperation() 用于方法;表示一个http请求的操作 
	value用于方法描述 
	notes用于提示内容 
	tags可以重新分组(视情况而用) 
@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等) 
	name–参数名 
	value–参数说明 
	required–是否必填
@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上 
	示例:
		@Api(value="用户controller",tags={"用户操作接口"})
		@RestController
		public class UserController {
		     @ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
		     @GetMapping("/getUserInfo")
		     public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
		     // userService可忽略,是业务逻辑
		      User user = userService.getUserInfo();
		
		      return user;
		  }
		  @ApiIgnore//使用该注解忽略这个API
          @RequestMapping(value = "/hi", method = RequestMethod.GET)
          public String  jsonTest() {
               return " hi you!";
          }
		}
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收 
	value–表示对象名 
	description–描述 
	都可省略 
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改 
	value–字段说明 
	name–重写属性名字 
	dataType–重写属性类型 
	required–是否必填 
	example–举例说明 
	hidden–隐藏
	   示例:
			@ApiModel(value="user对象",description="用户对象user")
			public class User implements Serializable{
			    private static final long serialVersionUID = 1L;
			     @ApiModelProperty(value="用户名",name="username",example="xingguo")
			     private String username;
			     @ApiModelProperty(value="状态",name="state",required=true)
			      private Integer state;
			      private String password;
			      private String nickName;
			      private Integer isDeleted;
			
			      @ApiModelProperty(value="id数组",hidden=true)
			      private String[] ids;
			      private List<String> idList;
			     //省略get/set
			}

			  @ApiOperation("更改用户信息")
			  @PostMapping("/updateUserInfo")
			  public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
			
			     int num = userService.updateUserInfo(user);
			     return num;
			  }
@ApiImplicitParam() 用于方法 
	表示单独的请求参数 
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam 
	name–参数ming 
	value–参数说明 
	dataType–数据类型 
	paramType–参数类型 
	  示例:
		@ApiOperation("查询测试")
	    @GetMapping("select")
	   //@ApiImplicitParam(name="name",value="用户名",dataType="String", paramType = "query")
	    @ApiImplicitParams({
	    @ApiImplicitParam(name="name",value="用户名",dataType="string", paramType = "query",example="xingguo"),
	    @ApiImplicitParam(name="id",value="用户id",dataType="long", paramType = "query")})
	    public void select(){		
	    }

4,访问 swagger2 的 UI 界面

4.1,默认的 UI 界面访问地址

swagger2 的 UI 地址默认使用 http://youIp:port/swagger-ui.html 来访问

4.2,自定义 swagger2 UI 访问地址

如想要自定义访问路径,按照此博客步骤操作即可:https://blog.csdn.net/u012954706/article/details/81086244

如下图所示:在这里插入图片描述

5,安全起见,生产环境应当关闭swagger文档
可以通过以下两种方式进行关闭:

5.1,使用 @ConditionalOnProperty 注解

1. 在 swagger 的配置类上增加 @ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true")  注解
2. 在 application.yml 或者 application.properties 文件中增加如下配置
	swagger.enable=false  # 关闭
    swagger.enable=true   # 开启

5.2,使用 @Profile 注解

1. 在 swagger 配置类上增加 @Profile{"dev, local"} 注解,注解中指定的是开启 swagger2 UI 界面的环境,这里指定的是本地和开发环境
2. 配置多套环境的 application.properties 文件,在主配置文件中指定使用的环境
    spring.profiles.active=local  
   # spring.profiles.active=prod

关闭时展示的页面,如下图所示:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38946877/article/details/85316929