本文介绍如何在spring Boot项目中集成Swagger,方便API文档的生成和测试。 以下步骤将指导您完成集成过程:
1. 添加依赖项:
在您的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>
请根据您的项目需求选择合适的版本号。
2. Swagger配置:
创建一个名为SwaggerConfig.Java的类,并添加以下代码:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; 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 api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("your.base.package")) //替换为您的控制器包名 .paths(PathSelectors.any()) .build(); } }
记住将”your.base.package”替换成您spring boot项目中控制器类的包名。
3. 访问Swagger UI:
启动Spring Boot应用后,在浏览器中访问以下URL:
http://localhost:8080/swagger-ui.html
您应该能够看到Swagger UI界面,其中列出了所有可用的API。
4. 高级配置 (可选):
您可以进一步自定义Swagger配置,例如添加API信息、全局参数等。以下是一个更详细的配置示例:
import springfox.documentation.builders.*; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { List<Parameter> params = new ArrayList<>(); params.add(new ParameterBuilder() .name("Authorization") .description("Access token") .modelRef(new ModelRef("string")) .parameterType("header") .required(false) .build()); ApiInfo apiInfo = new ApiInfoBuilder() .title("My API") .description("My API description") .version("1.0.0") .contact("Your Name") .build(); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo) .select() .apis(RequestHandlerSelectors.basePackage("your.base.package")) //替换为您的控制器包名 .paths(PathSelectors.any()) .build() .globalOperationParameters(params); } }
完成以上步骤后,您就成功将Swagger集成到Spring Boot项目中了,可以使用Swagger UI方便地浏览和测试您的API。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END