spring boot 基础案例使用Swagger2构建强大的API文档
在Spring Boot项目中使用Swagger2构建API文档,你需要以下步骤:
- 添加Swagger2依赖到
pom.xml
文件中:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- 创建Swagger2配置类
SwaggerConfig.java
:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"My API Title",
"My API Description",
"1.0",
"urn:tos",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
}
}
- 在你的控制器类中使用
@Api
和@ApiOperation
注解来描述API:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@Api(value = "测试控制器", description = "用于演示Swagger2的使用")
public class TestController {
@GetMapping("/test")
@ApiOperation(value = "测试API", notes = "用于测试Swagger2集成")
public String test() {
return "success";
}
}
- 运行Spring Boot应用,并访问
http://localhost:8080/swagger-ui.html
来查看Swagger文档。
以上步骤可以帮助你在Spring Boot项目中集成和使用Swagger2构建API文档。
评论已关闭