How to use SpringBoot integrated interface management tool Swagger
1. Introduction to Swagger
Swagger is a series of RESTful API tools. Through Swagger, you can get an interactive document of the project, automatic generation of client SDK and other functions.
The goal of Swagger is to define a standard, language-independent interface for REST APIs, so that people and computers can't see the source code or documents or can't pass network traffic detection. Ability to discover and understand the functionality of various services. When services are defined through Swagger, consumers can interact with remote services with a small amount of implementation logic.
2. Springboot integrates swagger
The idea of using Spring Boot to integrate Swagger is to use annotations to mark the information that needs to be displayed in the API document. Swagger will use the annotations marked in the project to mark the information. Generate corresponding API documentation. Swagger is known as the most popular API tool in the world. It provides a complete solution for API management. The factors that need to be considered for API document management are basically included. Here we will explain the most commonly used customization content.
1. Add swagger coordinates
Spring Boot integrates Swagger 3. It is very simple. You only need to introduce dependencies and do basic configuration.
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
2. Swagger Helloword implementation
2.1. Create springboot project
Add the @EnableOpenApi annotation to the startup class to enable the swagger api document function
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.oas.annotations.EnableOpenApi; @SpringBootApplication @EnableOpenApi //启动swagger api文档注解 public class SpringBootWithSwaggerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootWithSwaggerApplication.class, args); } }
2.2. Write an interface
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author 阿水 * @create 2023-04-11 9:54 */ @RestController() public class SwaggerController { @GetMapping ("hello") public String hello(String params) { return "hello swagger"+" param为:"+params; } }
2.3. Access address
http://localhost:8080/swagger-ui/index.html
Swagger indicates through annotations that the interface will generate documents, including interface name, request method, parameters, return information, etc. 1,
Api annotations and ApiOperation annotations
@Api
语法: @Api(tags = "用户操作") 或 @Api(tags = {"用户操作","用户操作2"})
@ApiOperation
语法: @ApiOperation(value = "", notes = "", response = ) 属性说明: value:方法说明标题 notes:方法详细描述 response:方法返回值类型Case: Use @Api and @ApiOperation to generate api documents
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author 阿水 * @create 2023-04-11 9:54 */ @RestController() @Api(tags = {"操作用户"}) public class SwaggerController { @GetMapping ("hello") @ApiOperation(value = "swagger请求",notes = "阿水的第一个swagger请求",response = String.class) public String hello(String params) { return "hello swagger"+" param为:"+params; } }2,
ApiImplicitParams annotations and ApiImplicitParam
@ApiImplicitParams annotations and @ApiImplicitParam are used for non-object parameters (parameter binding) in methods Use when arriving at a simple type.) Explain
语法: @ApiImplicitParams(value = { @ApiImplicitParam(name="", value = "", type = "", required = true, paramType = "", defaultValue = "") }) 属性说明: name:形参名称 value:形参的说明文字 type:形参类型 required:该参数是否必须 true|false paramType: 用于描述参数是以何种方式传递到 Controller 的,它的值常见有: path, query, body 和 header path 表示参数是『嵌在』路径中的,它和 @PathVariable 参数注解遥相呼应; query 表示参数是以 query string 的形式传递到后台的(无论是 get 请求携带在 url 中,还是 post 请求携带在请求体中),它和 @RequestParam 参数注解遥相呼应; header 表示参数是『藏在』请求头中传递到后台的,它和 @RequestHeader 参数注解遥相呼应的。 form 不常用. defaultValue :参数默认值Note: The name attribute of @ApiImplicitParam should echo the value of @RequestParam or @PathVariable. Case: Use @ApiImplicitParams annotation and @ApiImplicitParam to describe method parameters
import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author 阿水 * @create 2023-04-11 9:54 */ @RestController() @Api(tags = {"操作用户"}) public class SwaggerController { @GetMapping ("hello") @ApiOperation(value = "swagger请求",notes = "阿水的第一个swagger请求",response = String.class) @ApiImplicitParams(value ={ @ApiImplicitParam(name="param1", value = "参数名1", type = "String", required = true, paramType = "query", defaultValue = "阿水所想的默认值1" ), @ApiImplicitParam(name="param2", value = "参数名2", type = "String", required = true, paramType = "query", defaultValue = "阿水所想的默认值2" ) }) public String hello(String param1,String param2) { return "hello swagger"+" param1为:"+param1+"param2为"+param2; } }
##3, ApiModel annotation and ApiModelProperty
- @ApiModel
-
is used on entity classes to describe the class and is used for parameter reception instructions in entity classes.
@ApiModel("用户类") @Data public class Users { @ApiModelProperty(value = "编码:主键") private Integer id; @ApiModelProperty(value = "用户名") private String username; @ApiModelProperty(value = "密码") private String password; }
4. ApiResponse and ApiResponses
@ApiResponses annotation and @ApiResponse annotation are marked on the Controller method to describe the response of the HTTP request
/** * 添加用户 * * @param user * @return */ @PostMapping("/add") @ApiOperation(value = "添加用户",notes = "添加用户信息",response = ResponseResult.class) @ApiResponses({ @ApiResponse(code = 200, message = "添加成功", response = ResponseResult.class), @ApiResponse(code = 500, message = "添加失败", response = ResponseResult.class) }) public ResponseResult<Void> addUser(@RequestBody User user) { //获得生成的加密盐 user.setSalt(SaltUtils.getSalt()); int n = userService.addUser(user); if (n > 0) { return new ResponseResult<Void>(200, "添加成功"); } return new ResponseResult<Void>(500, "添加失败"); }
5. Create the SwaggerConfig configuration class
Add two methods in SwaggerConfig: (one method is to make auxiliary preparations for the other method)
api() method uses @Bean, Initialized at startup, the instance Docket (Swagger API summary object) is returned. What needs to be noted here is that .apis(RequestHandlerSelectors.basePackage("xxx.yyy.zzz")) specifies the package path that needs to be scanned. Only the Controller under this path Classes will automatically generate Swagger API documentation.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * Swagger配置类 */ @Configuration //项目启动时加载此类 public class SwaggerConfig { @Bean public Docket api(){ return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() // 此处自行修改为自己的 Controller 包路径。 .apis(RequestHandlerSelectors.basePackage("com.lps.controller")) .paths(PathSelectors.any()) .build(); } public ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("阿水的项目接口文挡") .description("阿水的 Project Swagger2 UserService Interface") //说明信息 .termsOfServiceUrl("http://localhost:8080/swagger-ui/index.html") //文档生成的主页地址 .version("1.0") //文档版本 .build(); } }
apiInfo() method configuration is relatively important. The basic information displayed on the main configuration page includes title, description, version, terms of service, etc. If you look at the source code of the ApiInfo class, you will also find more configurations such as license support.
4. Springsecurity integrates swagger
4.1, configures the release address
http.authorizeRequests().antMatchers( "/swagger-ui.html", "/swagger-ui/*", "/swagger-resources/**", "/v2/api-docs", "/v3/api-docs", "/webjars/**").permitAll() .anyRequest().authenticated();
4.2, replaces the UI
The entire process above has been completed, but the generated In fact, many people don't like the interface document page, and feel that it is not in line with the usage habits of Chinese people. Therefore, some experts have provided other UI test pages. The use of this page is quite extensive.
Import the following dependencies, restart the project and access the address: http://localhost:8080/doc.html
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency>
The above is the detailed content of How to use SpringBoot integrated interface management tool Swagger. For more information, please follow other related articles on the PHP Chinese website!

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

ToeffectivelytestJavaapplicationsforplatformcompatibility,followthesesteps:1)SetupautomatedtestingacrossmultipleplatformsusingCItoolslikeJenkinsorGitHubActions.2)ConductmanualtestingonrealhardwaretocatchissuesnotfoundinCIenvironments.3)Checkcross-pla

The Java compiler realizes Java's platform independence by converting source code into platform-independent bytecode, allowing Java programs to run on any operating system with JVM installed.

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.


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 CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

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.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
