Table of Contents
Introduce Swagger2 dependency
Create configuration file
Home Java javaTutorial SpringBoot integrates Swagger2 to generate interface documents, and my mother no longer has to worry about me writing API documents.

SpringBoot integrates Swagger2 to generate interface documents, and my mother no longer has to worry about me writing API documents.

May 26, 2020 pm 06:36 PM
1

In the current development process, basically all system development has been carried out using API interfaces. Therefore, in this process, a good API document has become the backend and frontend for communication and development. key bridge.

The traditional approach is for developers to create a RESTful API document to record all interface details. To be honest, such a workload is not small and very trivial, and as the project is updated The following problems will occur.

  • Documentation is difficult to maintain.

  • The interface content is more complex and the writing efficiency is lower.

Swagger is to solve this problem. As a standardized and complete framework, it can be used to generate, describe, call and visualize RESTful style Web services:

Through Swagger, we can automatically generate/update API interface documents by using annotations during the interface development process, and support debugging of the interface on the document page.

Next, let’s briefly talk about how to integrate Swagger2 in SpringBoot (2 represents its version)

Introduce Swagger2 dependency

pom.xml file

<dependencies>
        <!--Swagger2 在此,个人推荐使用2.8.0版本,较为稳定-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
</dependencies>
Copy after login

Create configuration file

Swagger2Config.java java configuration file

@Configuration
// 指定扫描的api包路径
@ComponentScan(basePackages = {"cn.beatree.xxx.controller"})
//注解开启 swagger2 功能
@EnableSwagger2
public class Swagger2Config {
    @Value("${swagger2.enable}")
    boolean enable;
    // 配置文件中通过值注入控制生产环境与开发环境下的启用状态
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enable)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("ANONVOTE | Swagger API文档")//标题
                .description("description: ANONVOTE | Swagger API文档")//描述
                .contact("BEATREE")//作者信息
                .version("1.0.0")//版本号
                .build();
    }
}
Copy after login

application.yml Configuration file

swagger2:
  enable: false #true 启用
Copy after login

@Configuration Annotation, specified as a configuration class, will be loaded when SpringBoot starts.

@EnableSwagger2 annotation to enable Swagger2.

Member methods createRestApi After the function creates the Docket Bean, apiInfo() Basic information used to create the API (these basic information will be displayed in the documentation page). The select() function returns an ApiSelectorBuilder Instances are used to control which interfaces are exposed to Swagger for display. In this example, they are defined by specifying the scanned package path. Swagger will scan all Controllers under the package. Defines the API and produces documentation content (except for requests specified by @ApiIgnore).

Commonly used Swagger annotations

@Api: Modify the entire class and describe the role of the Controller

@ApiOperation: Describe a method of a class, or an interface

@ApiParam: Description of a single parameter @ApiModel: Use an object to Receive parameters

@ApiProperty: When using an object to receive parameters, describe a field of the object

@ApiResponse: One description of the HTTP response

@ApiResponses: The overall description of the HTTP response

@ApiIgnore : Use this annotation to ignore this API

@ApiError : Information returned when an error occurs

@ApiImplicitParam: Describes a request parameter, you can configure the Chinese meaning of the parameter, and you can also set the default value for the parameter

@ApiImplicitParams: Describes a request parameter list consisting of multiple

@ApiImplicitParam annotated parameters

For example

@RestController
@Transactional    // 事务注解,实现回滚
@RequestMapping("/api/tlink")
@Api(value = "/api/tlink", tags = "参与者相关接口")
public class TlinkController{
    @GetMapping("/checkCode/{code}")
    @ApiOperation(value = "投票认证码核验接口",
            notes = "该接口用于核验认证码合法性,对于投票主题内容的获取需后续调用Topic相关接口。返回值data中带有参数 topic & options")
    public JSONObject checkCode(@PathVariable("code") String code){
  ...
 }
}
Copy after login

Finally, after running the SpringBoot project, access it through the server address /swagger-ui.html.

It should be noted that if a path interceptor has been added, the swagger path needs to be released through

.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
Copy after login

.

The above is the detailed content of SpringBoot integrates Swagger2 to generate interface documents, and my mother no longer has to worry about me writing API documents.. 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

Video Face Swap

Video Face Swap

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

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)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles