Spring Boot整合swagger3

it2026-02-23  8

第一步创建一个spring boot 项目

第二步 pom.xml里引入包

<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>

第三步 创建SwaggerConfig 类

@Configuration public class SwaggerConfig { Boolean swaggerEnabled=true; @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()) // 是否开启 .enable(swaggerEnabled).select() // 扫描的路径包 .apis(RequestHandlerSelectors.basePackage("com.example.play")) // 指定路径处理PathSelectors.any()代表所有的路径 .paths(PathSelectors.any()).build().pathMapping("/"); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("SpringBoot-Swagger3集成和使用-demo示例") .description("springboot | swagger") // 作者信息 .contact(new Contact("name", "个人主页url", "email")) .version("1.0.0") .build(); } }

第四步 创建HelloController

package com.example.play.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @Api(value = "desc of class") public class HelloController { @ApiOperation(value = "desc of method", notes = "") @RequestMapping("/hello") public String hello() { return "Hello Spring Boot!"; } @ApiOperation(value = "hello one", notes = "") @GetMapping(value="/hello1") public Object hello( /* 参数注解 */ @ApiParam(value = "desc of param" , required=true ) @RequestParam String name) { return "Hello " + name + "!"; } }

第五步 启动类添加注解 @EnableOpenApi

结果

访问地址http://localhost:8080/swagger-ui/

这个界面有些繁琐,换一个更简洁的,pom文件引用包

<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency>

新的访问地址  http://localhost:8080/doc.html

最新回复(0)