Swagger


1. Add dependencies

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>
Copy the code

2. Write configuration classes

2.1. Single grouping

@Configuration
@EnableSwagger2
@Profile({"dev", "test"}) // This parameter takes effect only in the dev and test environment
public class SwaggerConfiguration {

    @Bean
    public Docket defaultApi1(a) {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiIanfo()).
                groupName("1.0").
                select().
                apis(RequestHandlerSelectors.basePackage("com.zhf.stujpa.controller")).
                paths(PathSelectors.any()).
                build();
    }

    public ApiInfo apiIanfo(a){
       return new ApiInfoBuilder().
                title("My test interface").
                description("My test interface").
                contact(new Contact("Zhang Haifeng"."http://XX.com"."[email protected]")). build(); }}Copy the code

2.2. Multiple groups

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket defaultApi1(a) {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiIanfo()).
                groupName("User controller").
                select().
                apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller.user")).
                Ant ("/ API /station/operation/**") */
            	paths(PathSelectors.any()).
                build();
    }

    public ApiInfo apiIanfo(a){
       return new ApiInfoBuilder().
                title("My test interface").
                description("My test interface").
                contact(new Contact("Zhang Haifeng"."http://XX.com"."[email protected]")).
                build();
    }
     @Bean
    public Docket defaultApi1(a) {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiIanfo()).
                groupName("Character Controller").
                select().
                apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller.role")). paths(PathSelectors.any()). build(); }}Copy the code

Knife4j


1. Add dependencies

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.7</version>
</dependency>
Copy the code

2. Write configuration classes

2.1. Single grouping

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "defaultApi1")
    public Docket defaultApi1(a) {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // Group name
                .groupName("2. X version")
                .select()
                // Specify the Controller scan package path
                .apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
  
  public ApiInfo apiIanfo(a){
       return new ApiInfoBuilder().
                title("My test interface").
                description("My test interface").
                contact(new Contact("Zhang Haifeng"."http://XX.com"."[email protected]")). build(); }}Copy the code

2.2. Multiple groups

  • Create the configuration property class /
@Data
@ConfigurationProperties(prefix = "stu.swagger")
public class SwaggerProperties {
    private String title = "Online Documents"; / / title
    private String group = ""; // Customize the group name
    private String description = "Online Documents"; / / description
    private String version = "1.0"; / / version
    private Contact contact = new Contact(); / / the contact
    private String basePackage = "com.zhf.stu"; // Swagger resolves the packet path
    private List<String> basePath = new ArrayList<>(); // The url rule that Swagger parses
    private List<String> excludePath = new ArrayList<>();// Url rules that need to be excluded based on basePath
    private Map<String, DocketInfo> docket = new LinkedHashMap<>(); // Group documents
	public String getGroup(a) {
        if (group == null || "".equals(group)) {
            return title;
        }
        return group;
    }
    @Data
    public static class DocketInfo {
        private String title = "Online Documents"; / / title
        private String group = ""; // Customize the group name
        private String description = "Online Documents"; / / description
        private String version = "1.0"; / / version
        private Contact contact = new Contact(); / / the contact
        private String basePackage = ""; // Swagger resolves the packet path
        private List<String> basePath = new ArrayList<>(); // The url rule that Swagger parses
        private List<String> excludePath = new ArrayList<>();// The url that needs to be excluded based on basePath
        public String getGroup(a) {
            if (group == null || "".equals(group)) {
                return title;
            }
            returngroup; }}@Data
    public static class Contact {
        private String name = "pinda"; / / the contact
        private String url = ""; // Contact URL
        private String email = ""; // Contact email}}Copy the code
  • Create the application.yml file
server:
  port: 10086
stu:
  swagger:
    enabled: true # Enable swagger
    docket:
      user:
        title: User modules
        base-package: com.zhf.stu.controller.user
      menu:
        title: Role module
        base-package: com.zhf.stu.controller.role
Copy the code
  • Create the configuration class SwaggerAutoConfiguration
@Configuration
@ConditionalOnProperty(name = "pinda.swagger.enabled", havingValue = "true", matchIfMissing = true)
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration implements BeanFactoryAware {
    @Autowired
    SwaggerProperties swaggerProperties;
  
    private BeanFactory beanFactory;
    @Bean
    @ConditionalOnMissingBean
    public List<Docket> createRestApi(a){
        ConfigurableBeanFactory configurableBeanFactory = 
            								(ConfigurableBeanFactory) beanFactory;
        List<Docket> docketList = new LinkedList<>();
        // No grouping
        if (swaggerProperties.getDocket().isEmpty()) {
            Docket docket = createDocket(swaggerProperties);
            configurableBeanFactory.registerSingleton(swaggerProperties.getTitle(), 
                                                      docket);
            docketList.add(docket);
            return docketList;
        }
        // Create a group
        for (String groupName : swaggerProperties.getDocket().keySet()){
            SwaggerProperties.DocketInfo docketInfo = 
                swaggerProperties.getDocket().get(groupName);
            ApiInfo apiInfo = new ApiInfoBuilder()
                    // Page title
                    .title(docketInfo.getTitle())
                    / / founder
                    .contact(new Contact(docketInfo.getContact().getName(),
                            docketInfo.getContact().getUrl(),
                            docketInfo.getContact().getEmail()))
                    / / version number
                    .version(docketInfo.getVersion())
                    / / description
                    .description(docketInfo.getDescription())
                    .build();

            / / base - path processing
            // Parse /** when no path is configured
            if (docketInfo.getBasePath().isEmpty()) {
                docketInfo.getBasePath().add("/ * *");
            }
            List<Predicate<String>> basePath = new ArrayList<>();
            for (String path : docketInfo.getBasePath()) {
                basePath.add(PathSelectors.ant(path));
            }

            / / exclude - path processing
            List<Predicate<String>> excludePath = new ArrayList<>();
            for (String path : docketInfo.getExcludePath()) {
                excludePath.add(PathSelectors.ant(path));
            }

            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo)
                	.groupName(docketInfo.getGroup())
                    .select()
                    // is the current package path
                    .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
                    .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
                    .build();
            configurableBeanFactory.registerSingleton(groupName, docket);
            docketList.add(docket);
        }
        return docketList;
    }

    // Build API documentation details
    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder()
                // Page title
                .title(swaggerProperties.getTitle())
                / / founder
                .contact(new Contact(swaggerProperties.getContact().getName(),
                                        swaggerProperties.getContact().getUrl(),
                                        swaggerProperties.getContact().getEmail()))
                / / version number
                .version(swaggerProperties.getVersion())
                / / description
                .description(swaggerProperties.getDescription())
                .build();
    }

    // Create an interface document object
    private Docket createDocket(SwaggerProperties swaggerProperties) {
        // Basic API information
        ApiInfo apiInfo = apiInfo(swaggerProperties);

        / / base - path processing
        // Parse /** when no path is configured
        if (swaggerProperties.getBasePath().isEmpty()) {
            swaggerProperties.getBasePath().add("/ * *");
        }
        List<Predicate<String>> basePath = new ArrayList<>();
        for (String path : swaggerProperties.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        / / exclude - path processing
        List<Predicate<String>> excludePath = new ArrayList<>();
        for (String path : swaggerProperties.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .groupName(swaggerProperties.getGroup())
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
                .build();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory; }}Copy the code

Commonly used annotations


@Api

Used with classes, this annotation marks a Controller (Class) as a Swagger resource (API).

  • Tags API Group tags. Apis with the same tags will be merged and displayed in a group.
  • Value If the tags are not defined, the value is used as the Api tags

@ApiOperation

Describes an operation or HTTP method on a specified (routed) path. Different operations with the same path are grouped into the same action object.

  • Value Indicates the operation description. The value contains 120 characters and 60 Chinese characters.
  • Notes a detailed description of the operation.
  • HttpMethod Specifies the action name of the HTTP request. Possible values are “GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS”, and “PATCH”.
  • Code defaults to 200 and must conform to the standard HTTP Status Code Definitions.

@ApiImplicitParams

For methods, annotate the Container class ApiImplicitParam, stored as an array.

@ApiImplicitParam

Annotate a single parameter to an API. Although the @APIParam annotation is bound to JAX-RS parameters, the @APIIMPLicitParam annotation defines the parameter list in a uniform way that is unique in Servelet and non-JAX-RS environments.

@ApiParam

Added the description of meta information about parameters. This annotation can only be used with jax-RS 1.x/2.x integration. Its main properties are

  • Required Specifies whether the parameter is required. The default value is false
  • Value Brief description of the parameter

@ApiResponses

Annotation @apiResponse wrapper class, array structure. Even if you need to use an @ApiResponse annotation, you need to include the @APIResponse annotation within the @apiresponses annotation.

@ApiResponse

Describes the possible results of an operation. This annotation can be used to describe all possible success and error codes when a REST API request occurs. You may or may not use this annotation to describe the return type of an operation, but the return type for a successful operation must be defined in @apiOperation. If the API has different return types, you need to define the return values separately and associate the return types. But Swagger does not support the same return code, multiple return type annotation. Note: This annotation must be included in the @apiresponses annotation.

  • Code Indicates the return code of the HTTP request. Valid values must comply with the standard HTTP Status Code Definitions.
  • Message A text message that is easier to understand
  • Response Returns type information, which must be fully qualified with the class name, such as “com.xyz.cc.person.class”.
  • ResponseContainer If the return type is container type, you can set the corresponding value. Valid values are “List”, “Set” or “Map”, and any other invalid values are ignored.

@ApiModel

Describe information about a Model (typically used when request parameters cannot be described using the @apiIMPLicitParam annotation)

  • The alias of the value Model, which defaults to the class name
  • Description Detailed description of the model

@ApiModelProperty

Describes the properties of a model

  • Value Brief description of the property
  • Example value for the example property
  • Required Whether the value is required

If you get something, give it a thumbs up