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

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

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 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.

See all articles