SpringCloud技术集成Swagger
在Spring Cloud项目中集成Swagger可以帮助开发者生成API文档,并提供在线测试功能。以下是一个简单的例子,展示如何在Spring Cloud项目中集成Swagger 2.x版本。
- 添加Swagger依赖到你的
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>
- 创建一个Swagger配置类:
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<>()
);
}
}
- 在你的Controller类中使用Swagger注解来描述API:
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@RestController
@Api(value = "User Controller", description = "Operations about user")
public class UserController {
@ApiOperation(value = "Get user by ID", response = User.class)
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "User not found")
})
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long id) {
// ...
retur
评论已关闭