springmvc springboot集成swagger2配置实现

3 篇文章 0 订阅
本文介绍了如何将Swagger2集成到Spring MVC和Spring Boot应用中,包括引入依赖、配置静态资源映射、Java配置 Swagger2、定义Swagger2的API基本信息以及指定暴露的接口。最后展示了在浏览器中查看Swagger2生成的API文档页面。
摘要由CSDN通过智能技术生成

一、首先需要引用swagger2的包

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

二、在spring-mvc.xml中添加映射静态的配置

<mvc:default-servlet-handler />

三、java中swagger2的配置类

/** 引用包已忽略 */
@Configuration
@EnableSwagger2
public class Swagger {
    //该方法为默认显示
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo("对外相关接口", "对外(C端)相关接口", "1.0"))
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }
    //新建分组
    @Bean
    public Docket stat_api() {
        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/stat/**")).build().groupName("统计相关接口").pathMapping("/")
                .apiInfo(apiInfo("统计相关接口", "文档中可以查询及测试接口调用参数和结果", "1.0"));
    }
 private ApiInfo apiInfo(String name, String description, String version) {
        ApiInfo apiInfo = new ApiInfoBuilder().title(name).description(description).version(version).build();
        return apiInfo;
    }
}
  • 首先通过@Configuration注解,让Spring来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2。
  • 其次通过createRestApi函数创建Docket的Bean之后,使用apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
  • 再次通过select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容,这里除了被@ApiIgnore指定的请求。

四、实际应用代码,类似如图:

/** 引用包已忽略 */
@RestController
@RequestMapping("user")
@Api
public class UsreInfoController {
    

    @ApiOperation(value = "获取用户列表",notes = "")
    @RequestMapping(value = "/getusers",method = RequestMethod.GET)
    public Object getDbType() {
        /** 忽略了方法体 */
        return null;
    }

    @ApiOperation(value = "根据用户ID获取用户信息",notes = "")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping("/getId/{id}")
    public Object getUserInfoByParmityKey(@PathVariable String id) {
        /** 忽略了方法体 */
        return null;
    }

}

五、常用注解

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
    
eg: @Api(tags = "用户信息Controller")



@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"
    
eg: @ApiOperation(value="用户登录",notes="手机号、密码都是必填!")



@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值
        
 eg: @ApiImplicitParams({
        @ApiImplicitParam(name="username",value="用户名",required=true,paramType="String"),
        @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
        @ApiImplicitParam(name="vcode",value="验证码",required=true,paramType="form",dataType="Integer")
		})



@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
        
 eg:@ApiOperation(value = "select1请求",notes = "多个参数,多种的查询参数类型")
     @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
         })

 
@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

eg: 
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import java.io.Serializable;

    @ApiModel(description= "返回响应数据")
    public class RestMessage implements Serializable{

        @ApiModelProperty(value = "是否成功")
        private boolean success=true;
        @ApiModelProperty(value = "返回对象")
        private Object data;
        @ApiModelProperty(value = "错误编号")
        private Integer errCode;
        @ApiModelProperty(value = "错误信息")
        private String message;

        /* getter/setter */
    }

六、

在浏览器打开:http://localhost:8080/swagger-ui.html
页面如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值