Spring Boot is a lightweight open source framework based on the Spring framework. Its emergence greatly simplifies the construction and development of Spring applications. In the development process, interface documentation is a very important part. It not only facilitates developers to view and understand the functions and parameters of the interface, but also helps front-end and back-end development work together to improve development efficiency.
1. About Swagger
Swagger is a specification and toolset for RESTful interface documents. Its goal is to unify the format and specifications of RESTful interface documents. In the development process, interface documentation is a very important part. It not only facilitates developers to view and understand the functions and parameters of the interface, but also helps front-end and back-end development work together to improve development efficiency. Spring Boot can integrate Swagger to automatically generate interface documents. By using annotations to describe interfaces, Swagger can automatically generate interface documents.
2. Swagger installation
1. Download Swagger
The official website of Swagger is https://swagger.io/, we can download the latest version of Swagger here .
2. Install Swagger
Just unzip the downloaded Swagger to the specified directory. This installation process is quite simple. In the unzipped directory, we can find the swagger-ui.html page, which is the UI interface of Swagger.
3. Use of Swagger
1. Writing interfaces
When writing interfaces, we need to use Swagger annotations to describe interface information. Commonly used annotations include:
@Api: Class or interface used to describe the interface
@ApiOperation: Method used to describe the interface
@ApiParam: used to describe the parameters of the interface
@ApiModel: used to describe the data model
@ApiModelProperty: Properties used to describe the data model
For example, we write a simple interface:
@RestController @Api(tags = "用户接口") public class UserController { @GetMapping("/user/{id}") @ApiOperation(value = "根据 ID 获取用户信息") public User getUserById(@ApiParam(value = "用户 ID", required = true) @PathVariable Long id) { // 根据 ID 查询用户信息 } }
In the above code, @Api represents the The class is a user interface, @ApiOperation indicates that the method is an interface for obtaining user information, @ApiParam indicates that the parameter is a user ID, and @PathVariable indicates that the parameter is a path parameter.
2. Enable Swagger
In Spring Boot, we can enable Swagger by adding Swagger-related dependencies.
We can add the following dependencies in the pom.xml file:
<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>
In Spring Boot, we also need to add a configuration class to configure Swagger. The code of the configuration class is as follows:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("接口文档") .description("接口文档") .version("1.0.0") .build(); } }
In the above code, @Configuration indicates that the class is a configuration class, and @EnableSwagger2 indicates that Swagger is enabled. In the api() method, we configure the scanned package path through the `select() method, configure the access path of the interface through the paths() method, and configure related information of the interface document through the apiInfo() method.
3. View the interface document
After starting the Spring Boot application, we can visit http://localhost:8080/swagger-ui.html in the browser to view the interface document. In the Swagger UI page, we can see all interface information, including interface name, request method, request path, request parameters, response parameters, etc.
4. Advanced use of Swagger
1. Describe the data model
We can use @ApiModel
and @ApiModelProperty
annotations to describe the data model and properties. For example, we can write a User class and use @ApiModel and
@ApiModelProperty 注解来描述该数据模型: @ApiModel(description = "用户信息") public class User { @ApiModelProperty(value = "用户 ID", example ="1") private Long id; @ApiModelProperty(value = "用户名", example = "张三") private String username; @ApiModelProperty(value = "密码", example = "123456") private String password; // 省略 getter 和 setter 方法 }
on the class. In the above code, @ApiModel indicates that the class is a data model, and @ApiModelProperty indicates that the property is a data model. Attribute, the value attribute represents the description of the attribute, and the example attribute represents the example value of the attribute.
2. Describing enumeration types
We can use @ApiModel
and @ApiModelProperty
annotations to describe enumeration types. For example, we can write a Gender enumeration type and use the @ApiModelProperty annotation on the enumeration value to describe the enumeration value:
@ApiModel(description = "性别") public enum Gender { @ApiModelProperty(value = "男") MALE, @ApiModelProperty(value = "女") FEMALE; }
In the above code, @ApiModel indicates that the enumeration type is a An enumeration type that describes gender. @ApiModelProperty indicates that the enumeration value is an enumeration value that describes men or an enumeration value that describes women.
3. Describe response parameters
We can use @ApiResponses and @ApiResponse annotations to define API response parameters. For example, we can write a getUserById() method and use @ApiResponses and @ApiResponse annotations on the method to describe the response parameters of the method:
@GetMapping("/user/{id}") @ApiOperation(value = "根据 ID 获取用户信息") @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = User.class), @ApiResponse(code = 404, message = "用户不存在") }) public User getUserById(@ApiParam(value = "用户 ID", required = true) @PathVariable Long id) { // 根据 ID 查询用户信息 }
In the above code, @ApiResponses represents the response of the method Parameters, @ApiResponse represents the description of the response parameters, the code attribute represents the response code, the message attribute represents the response message, and the response attribute represents the response data model.
5. Advanced use of Swagger
1. Configure global parameters
By using the method globalOperationParameters(), we can configure global parameters in the configuration class. We can authorize by configuring a global Authorization parameter
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .globalOperationParameters(Arrays.asList( new ParameterBuilder() .name("Authorization") .description("授权") .modelRef(new ModelRef("string")) .parameterType("header") .required(false) .build() )) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("接口文档") .description("接口文档") .version("1.0.0") .build(); } }
In the above code, we configure a global Authorization parameter for authorization through the globalOperationParameters() method.
2、配置安全协议
通过在配置类中调用 securitySchemes() 方法,我们能够进行安全协议的配置。举个例子,可以设置 Bearer Token 作为安全协议
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList( new ApiKey("Bearer", "Authorization", "header") )) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("接口文档") .description("接口文档") .version("1.0.0") .build(); } }
在上面的代码中,我们通过 securitySchemes() 方法来配置一个 Bearer Token 安全协议。
3、配置安全上下文
使用 securityContexts() 方法配置安全上下文是配置类中的一种可选方法。举个例子,我们可以设置一个安全上下文来在Swagger UI中展示认证按钮:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList( new ApiKey("Bearer", "Authorization", "header") )) .securityContexts(Collections.singletonList( SecurityContext.builder() .securityReferences(Collections.singletonList( new SecurityReference("Bearer", new AuthorizationScope[0]) )) .build() )) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("接口文档") .description("接口文档") .version("1.0.0") .build(); } }
在上面的代码中,我们通过 securityContexts() 方法来配置一个安全上下文,用于在 Swagger UI 中显示认证按钮。
4、配置忽略参数
在API文档中,可能有些参数包含敏感信息,因此需要保护这些信息不被公示。我们可以使用 @ApiIgnore 注解来忽略这些参数。在 User 类中,我们可以使用 @ApiIgnore 注解来排除密码参数
@ApiModel(description = "用户信息") public class User { @ApiModelProperty(value = "用户 ID", example = "1") private Long id; @ApiModelProperty(value = "用户名", example = "张三") private String username; @ApiModelProperty(hidden = true) @ApiIgnore private String password; // 省略 getter 和 setter 方法 }
在上面的代码中,@ApiModelProperty(hidden = true) 表示该参数是隐藏的,@ApiIgnore 表示忽略该参数。
The above is the detailed content of How does SpringBoot integrate Swagger?. For more information, please follow other related articles on the PHP Chinese website!

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
