SpringBoot integrates Swagger2 and uses it easily

1. Introduction to Swagger

To put it simply, Swagger is an API for the web backend interface. It is more used in front-end and back-end separation projects. It is mainly used to connect with the front-end. It follows the Restful API style!
For an introduction to swagger, you can directly see the official document

2. Introduced in the springboot web project

First create a new springboot web project, and then add swagger2 dependencies in the pom file!

2.1 Add Swagger dependency

You can find Swagger dependencies in the Maven warehouse . Here you need to add two dependencies, swagger2 and swagger ui, as follows:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2.2 Configuring the SwaggerConfig class

Create a new config package under the directory of the startup class of the springboot project, and create a new SwaggerConfig class in the package, the content is as follows:

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2  // 开启 Swagger2 localhost:9000/swagger-ui.html
public class SwaggerConfig {
    
    
}

Start the springboot project to use swagger, visit localhost:8080/swagger-ui.html
swagger2 Home

3. Simple use of Swagger

3.1 Modify the welcome page information

@Configuration
@EnableSwagger2  // 开启 Swagger2 localhost:9000/swagger-ui.html
public class SwaggerConfig {
    
    

    // 配置 Swagger2 的 bean 实例
    @Bean
    public Docket docket(){
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("X0235")
                .select()
                // RequestHandlerSelector:配置扫描接口的方式
                // basePackage:指定要扫描的包
                // any():扫描全部
                // none():不扫描
                .apis(RequestHandlerSelectors.basePackage("com.dublbo.swagger.controller"))
                .build();
    }

    // 配置 Swagger 信息
    private ApiInfo apiInfo(){
    
    
        Contact contact = new Contact("独步凌波", "https://www.baidu.com", "mail.163.com/dubulingbo");
        return new ApiInfo("这是Swagger测试文档",
                "留恋处,兰舟催发,执手相看泪眼,竟无语凝噎!",
                "v1.0",
                "https://www.github.com",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}

Guess you like

Origin blog.csdn.net/dubulingbo/article/details/107743661