search
HomeJavajavaTutorialHow does SpringBoot integrate 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 查询用户信息
        }
    }

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    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)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.