Table of Contents
1. About Swagger
2. Swagger installation
1. Download Swagger
2. Install Swagger
3. Use of Swagger
1. Writing interfaces
2. Enable Swagger
3. View the interface document
5. Advanced use of Swagger
1. Describe the data model
2. Describing enumeration types
3. Describe response parameters
1. Configure global parameters
2、配置安全协议
3、配置安全上下文
4、配置忽略参数
Home Java javaTutorial How does SpringBoot integrate Swagger?

How does SpringBoot integrate Swagger?

May 31, 2023 am 10:20 AM
springboot swagger

    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 查询用户信息
        }
    }
    Copy after login

    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>
    Copy after login

    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();
        }
    }
    Copy after login

    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 方法
    }
    Copy after login

    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;
    }
    Copy after login

    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 查询用户信息 
    }
    Copy after login

    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();
        }
     
    }
    Copy after login

    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();
        }
     
    }
    Copy after login

    在上面的代码中,我们通过 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();
        }
     
    }
    Copy after login

    在上面的代码中,我们通过 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 方法
    }
    Copy after login

    在上面的代码中,@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!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

    Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

    How to generate API documentation using Swagger in PHP How to generate API documentation using Swagger in PHP Jun 17, 2023 am 10:40 AM

    With the continuous development of web applications, API has become one of the standards for modern web application development. However, as the number and complexity of APIs increases, maintaining and documenting them becomes increasingly complex. To solve this problem, Swagger came into being. It is a tool for generating API documentation, making it easier for developers to maintain and document APIs, while also providing visual documentation and various other features. In this article, we will discuss how to use Swagger in PHP to generate a

    How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

    1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

    Laravel development: How to use Laravel Swagger to generate API documentation? Laravel development: How to use Laravel Swagger to generate API documentation? Jun 13, 2023 am 09:35 AM

    Laravel development: How to use LaravelSwagger to generate API documentation? When developing web applications, dealing with API documentation is often a tedious but essential task. Use Swagger to automatically generate and visualize API documentation. In Laravel development, we can use the LaravelSwagger extension package to easily generate SwaggerAPI documentation. This article will guide you how to use L

    How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

    Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

    Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

    SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

    How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

    1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

    How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

    When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

    See all articles