首页 > 其他分享 >【springboot】使用swagger生成接口文档

【springboot】使用swagger生成接口文档

时间:2024-09-05 18:51:56浏览次数:8  
标签:map springboot 响应 API 文档 new 注解 swagger

1. 添加依赖

      <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
        <version>2.6.0</version>
      </dependency>

        这里我老是添加不上这个依赖,搜索了下发现阿里云公共仓库中没有这个依赖,所以一直找不到。(阿里云仓库搜索

        于是修改了下maven的setting文件,添加了阿里云的中心仓库的镜像。

      <mirror>
          <id>aliyunmaven-central</id>
          <mirrorOf>*</mirrorOf>
          <name>阿里云中心仓库</name>
          <url>https://maven.aliyun.com/repository/central</url>
      </mirror>

2. 配置swagger

@Configuration
@ComponentScan
public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("API文档")
                        .version("1.0")
                        .description("Spring Boot 3.2.8项目的API文档")
                        .contact(new Contact().name("huan").email("[email protected]"))
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("外部文档")
                        .url("https://example.com/docs"));
    }
}

        配置完以上内容,访问localhost:8080/swagger-ui/index.html,可以跳转以下页面。

3. 使用Swagger注解来描述API

        控制器类

@RestController
@RequestMapping("resfood")
//@Tag注解用于为API接口分组,并提供分组的名称和描述
@Tag(name = "菜品api",description = "菜品管理相关接口")
public class ResfoodController {
    @Autowired
    private ResfoodService resfoodService;

    //{fid}结合@PathVariable实现rest风格url
    @GetMapping("getById/{fid}")
    public Map<String,Object> getById(
            // @PathVariable注解用于将请求路径中的参数绑定到方法参数上
            @PathVariable Integer fid){
        Map<String,Object> map = new HashMap<>();
        Resfood resfood = null;
        try {
            resfood = resfoodService.getById(fid);
        }catch (Exception e){
            e.printStackTrace();
            //设置状态码和提示信息
            map.put("code",0);
            map.put("msg","查询失败"+e.getCause());
            return map;
        }
        map.put("code",1);
        map.put("obj",resfood);
        return map;
    }
}

一些注解

  • @Tag注解:用于为API接口分组,并提供分组的名称和描述。

        控制类

        显示效果

  • @Operation注解:提供关于该方法操作的简要和详细描述。

        控制类

        显示效果

  • @ApiResponse注解:提供该方法的响应信息,如HTTP 响应码、响应的描述信息、响应的内容等。
    • @Content注解:描述响应的内容。
    • @Schema注解:指定响应内容的模式。

        控制类方法

        显示效果

4. 访问Swagger UI

        再次访问localhost:8080/swagger-ui/index.html,发现多了一些东西。

        展开可以看到以下信息。

5. 测试

        可以在swagger ui中发送测试数据,测试获得的响应json是否正确。打开某个请求路径,使用Try it out 按件后可以设置要测试的参数。

        Execute后可以得到响应结果。

        响应结果。

标签:map,springboot,响应,API,文档,new,注解,swagger
From: https://blog.csdn.net/BlackPudding_/article/details/141867013

相关文章