springboot集成swagger的应用

来源:互联网 发布:苍云脸型数据 编辑:程序博客网 时间:2024/06/05 10:16

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件

前后端分离的时候swagger可以减轻后端人员的文档编写的工作量;下面简单讲一下springboot集成swagger的过程以及用法;

首先maven引入swagger的依赖

<!-- Swagger --><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>

swagger的配置,如下javaconfig

@Configuration@EnableSwagger2public class SwaggerConfig {    @Bean        public Docket createRestApi() {        return new Docket(DocumentationType.SWAGGER_2)                .apiInfo(apiInfo())                .select()                                .apis(RequestHandlerSelectors.basePackage("com.xx.xxx"))                .paths(PathSelectors.any())                .build()                .useDefaultResponseMessages(false)                .enableUrlTemplating(false);    }    private ApiInfo apiInfo() {        return new ApiInfoBuilder()                .title("xxxxxxxxxxxxx接口")                .description("xxxxxx的详细说明")                .contact(new Contact("hym","https://xxx.xxxxxx.com.cn","xxxxxx@xxxx.com.cn"))                .version("1.0")                .build();    }}

@Configurationpublic class WebJarsConfig extends WebMvcConfigurerAdapter {    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("swagger-ui.html")        .addResourceLocations("classpath:/META-INF/resources/");        registry.addResourceHandler("/webjars/**")        .addResourceLocations("classpath:/META-INF/resources/webjars/");    }}

完成好上面的配置之后,我们访问http://ipaddress:port/swagger-ui.html即可


下面借鉴一下swagger的注解的含义,如下

一、相关注解解读
1. @Api

用在类上,说明该类的作用
@Api(value = "xxxxxxxx", description = "用户相关api")
2. @ApiOperation

用在方法上,说明方法的作用
@ApiOperation(value = "查找用户", notes = "查找用户", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
3 @ApiImplicitParams

用在方法上包含一组参数说明
4. @ApiImplicitParam

用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
paramType:参数放在哪个地方
header–>请求参数的获取:@RequestHeader
query–>请求参数的获取:@RequestParam
path(用于restful接口)–>请求参数的获取:@PathVariable
body(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传
value:参数的意思
defaultValue:参数的默认值

@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), })

5. @ApiResponses

用于表示一组响应

6. @ApiResponse

用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如”请求参数没填好”
response:抛出异常的类

@ApiResponses(value = {            @ApiResponse(code = 404, message = "No Name Provided")    })
7. @ApiModel

描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModel(value = "xxxxx")

8. @ApiModelProperty

描述一个model的属性
@ApiModelProperty(value = "xxxxxxx")


原创粉丝点击