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

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>

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

application.yml Configuration file

swagger2:
  enable: false #true 启用

@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){
  ...
 }
}

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/**")

.

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
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
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.