欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot使用Swagger2构建API文档

程序员文章站 2022-07-02 21:54:32
...
**SpringBoot使用Swagger2构建API文档**
第一步:在pom.xml中加入Swagger2的依赖
<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>

第二步:创建Swagger2配置类

package com.example.demo.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("springboot 开发文档")
                .description("李大牛")
                .termsOfServiceUrl("http://www.ujiuye.com/")
                .contact("Sunny")
                .version("1.0")
                .build();
    }
}

3、修改Controller增加文档注释
通过@ApiOperation 注解来给API增加说明 通过 @ApiImplicitParams @ApiImplicitParam 注解来给参数增加说明

/**
	 * 更新指定id用户信息
	 * @param id
	 * @param user
	 * @return
	 */
	@PutMapping("/{id}")
	@ApiOperation(value="更新指定id用户信息", notes="根据id更新用户信息")
	@ApiImplicitParams({
         @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
         @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
     })
	public String updateUser(@PathVariable("id") Long id,User user) {
		user.setId(id);
		userRepository.saveAndFlush(user);
		return "success";
	}
	
	/***
	 * 删除指定id用户
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ApiOperation(value="删除指定id用户信息", notes="根据id删除用户信息")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
	public String deleteUser(@PathVariable("id") Long id) {
		
		userRepository.deleteById(id);
			return "success";
		
	}

4、查看Swagger2文档
访问地址:http://localhost:8080/swagger-ui.html

SpringBoot使用Swagger2构建API文档