springboot swagger Quick Start

brief introduction

introduce

Maybe everyone has used swagger, which can display interface information through ui pages and quickly debug with the front end.

No contact with small partners can be referred to Official website The article has carried on the understanding. demo page.

Multi-application

Of course, in a single application you can configure SwaggerConfig class loaded build Docket, you can quickly build swagger.

The code is roughly as follows:

/**
 * Swagger2 Configuration class
 * When integrating with spring boot, it is placed in a directory at the same level as Application.java.
 * With the @Configuration annotation, let Spring load the class configuration.
 * Swagger2 is then enabled through the @Enable Swagger2 annotation.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    /**
     * Creating API applications
     * apiInfo() Adding API-related information
     * Returns an ApiSelectorBuilder instance through the select() function to control which interfaces are exposed to Swagger for presentation.
     * This example defines the directory that specifies the API to be created using the package path for the specified scan.
     * 
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    /**
     * Basic information for creating the API (which is displayed on the document page)
     * Access address: http://actual project address/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot Use Swagger2 structure RESTful APIs")
                .description("More attention http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("sunf")
                .version("1.0")
                .build();
    }
}

Modularization-Starter

Reason

Small partners who have developed micro services should have experienced it. When there are many micro-service modules, each module needs to configure such a class to load swagger. In extreme cases, after some friends duplicate Swagger Config of other modules for modification, they still find that swagger can not be loaded, resulting in clearly duplicated, why can't it be loaded, and checking the bug and its time-consuming.

On this basis, we can build a swagger-starter module, just need to refer to a jar, load some special configurations, you can quickly use some of the functions of swagger.

Design

Create the module swagger-spring-boot-starter.
The functions are as follows:

  1. Load SwaggerConfig.
  2. Configure swagger by configuring it.
  3. Enable loads annotations.

1. Create Swagger Config

SwaggerConfig is the same as before, but the configuration inside needs to be externalized.

@Configuration
@PropertySource(value = "classpath:swagger.properties", ignoreResourceNotFound = true, encoding = "UTF-8")
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

  @Resource
  private SwaggerProperties swaggerProperties;

  @Bean
  public Docket buildDocket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(buildApiInf())
        .select()
        .apis(RequestHandlerSelectors.basePackage(""))
        .paths(PathSelectors.any())
        .build();
  }

  private ApiInfo buildApiInf() {
    return new ApiInfoBuilder()
        .title(swaggerProperties.getTitle())
        .description(swaggerProperties.getDescription())
        .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
        .contact(new Contact("skyworth", swaggerProperties.getTermsOfServiceUrl(), ""))
        .version(swaggerProperties.getVersion())
        .build();
  }
}

2. Creating Swagger Properties configuration is relevant

Configuration loads swagger.properties in the resources directory through the @PropertySource annotation.

Create the SwaggerProperties configuration class, which contains some commonly used attributes for general swagger initialization, such as scanning package paths, title, and so on.

@Data
@ToString
@ConfigurationProperties(SwaggerProperties.PREFIX)
public class SwaggerProperties {

  public static final String PREFIX = "swagger";

  /**
   * Document Scan Packet Path
   */
  private String basePackage = "";

  /**
   * title For example: user module system interface details
   */
  private String title = "Details of System Interface of Shenlan Cloud Platform";

  /**
   * Introduction to Service Documents
   */
  private String description = "Online Documentation";

  /**
   * Terms of Service Website
   */
  private String termsOfServiceUrl = "https://www.deepblueai.com/";

  /**
   * Edition
   */
  private String version = "V1.0";


}

In order to make better use of configuration, we need to configure an additional-spring-configuration-metadata.json in idea, just like the official starter package, so that our own configuration can also have the function of prompting. Configuration Tips Configuration Tips Configuration Tips Configuration Tips Configuration Tips ...

3. Loading Swagger Config and other features

Because it's a starter module, maybe someone else's project directory and starter module's directory are inconsistent, leading to the SwaggerConfig class can not be loaded. We need to use spring.factories to load the SwaggerConfig class into the spring container.

resources/META-INF

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  io.purge.swagger.SwaggerConfig

This time, of course, Swagger Config is loaded based on Enable mode.

Create the @EnableSwaggerPlugins annotation class and use @Import(SwaggerConfig.class) to import SwaggerConfig into Dagong.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(SwaggerConfig.class)
@EnableSwagger2
public @interface EnableSwaggerPlugins {

}

Use

Adding dependencies

Write your own swagger through maven packaging, their own project reference.

<dependency>
  <groupId>com.purge.swagger</groupId>
  <artifactId>swagger-spring-boot-starter<factId>
  <version>0.1.0.RELEASE</version>
</dependency>

Configure the swagger.properties file

  • Create the swagger.properties configuration in the resources directory of your project module

  • swagger.properties is roughly configured as follows

swagger.basePackage="swagger Scanning project package path"
swagger.title="swagger Page Display Title"
swagger.description="swagger Introduction to Web Display"

The startup class adds the @EnableSwaggerPlugins annotation.

@EnableSwaggerPlugins
@SpringBootApplication
public class FrontDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(FrontDemoApplication.class, args);
  }

}

Visit http://ip:port/swagger-ui.html to check whether swagger-ui is normal.

summary

Simple starter code writing can reduce the complexity of the new module. Simple configuration is needed to use the corresponding features and reduce unnecessary errors in copying code.

Sample code address: swagger-spring-boot

Tags: Java Spring encoding JSON

Posted on Thu, 05 Sep 2019 21:48:16 -0700 by aiikcmo