catalogue
2. Add the configuration file resources \ config \ swagger properties
3. Write Swagger3Config configuration class
1. Add dependency
<!-- introduce swagger3 package --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <!-- introduce swagger-bootstrap-ui Package, optimization UI Page, can not add --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.8.5</version> </dependency>
2. Add the configuration file resources \ config \ swagger properties
swagger.documentation-type=oas_30 swagger.base-package=com.example.demo.db.controller swagger.api-info.title=demo_springboot swagger.api-info.description=xxx swagger.api-info.contact.name=JsonFling swagger.api-info.contact.email=jsonfling@xxxxxxxx.com swagger.api-info.contact.url=Shenzhen, Guangdong
3. Write Swagger3Config configuration class
package com.example.demo.db.config; import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.context.annotation.*; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import springfox.documentation.builders.*; import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.schema.ScalarType; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; /** * Description: Swagger will be started only when the Swagger configuration class profile contains any of dev, sit and UAT (i.e. Swagger will not be started in the production environment) * SPRING_PROFILES_ACTIVE=dev/sit/uat To enable this configuration */ @Configuration //@Profile({"dev", "test", "uat"}) @EnableOpenApi//The configuration will be started automatically, and the startup class does not need any annotation @EnableSwaggerBootstrapUI//Access beautification for easy viewing and debugging public class Swagger3Config { /** * @return Docket Is the swagger global configuration object */ @Bean public Docket createApi(SwaggerProperties properties) { return new Docket(properties.getDocumentationType().value) .apiInfo(createApiInfo(properties)) .select() // Specify the package to be scanned. If it is not specified, the interface of the spring framework will be scanned. If it is specified incorrectly, the interface will not be scanned .apis(RequestHandlerSelectors .basePackage(properties.getBasePackage())) .paths(PathSelectors.any()) .build() .globalRequestParameters(getGlobalRequestParameters())//Add general input parameters .globalResponses(HttpMethod.POST, getGlobalResonseMessage());//The post method adds a general response header } /** * API Basic information of the document, including title, contact, etc * @return ApiInfo */ private ApiInfo createApiInfo(SwaggerProperties properties) { SwaggerApiInfo apiInfoMeta = properties.getApiInfo(); SwaggerApiInfoContact contactMeta = apiInfoMeta.getContact(); Contact contact = new Contact(contactMeta.getName(), contactMeta.getUrl(), contactMeta.getEmail()); return new ApiInfoBuilder() .title(apiInfoMeta.getTitle()) .description(apiInfoMeta.getDescription()) .contact(contact) .build(); } //Define document type and configure file configuration public enum DocumentationTypeMode { /** * SWAGGER_12 */ SWAGGER_12(DocumentationType.SWAGGER_12), /** * SWAGGER_2 */ SWAGGER_2(DocumentationType.SWAGGER_2), /** * OAS_30 */ OAS_30(DocumentationType.OAS_30); private final DocumentationType value; DocumentationTypeMode(DocumentationType value) { this.value = value; } } @Component @PropertySource(value = "classpath:/config/swagger.properties", ignoreResourceNotFound = true, encoding = "UTF-8") @ConfigurationProperties(prefix = "swagger") public static class SwaggerProperties { private DocumentationTypeMode documentationType = DocumentationTypeMode.OAS_30; private String basePackage = "com.example.demo.db.controller"; private SwaggerApiInfo apiInfo = new SwaggerApiInfo(); public DocumentationTypeMode getDocumentationType() { return documentationType; } public void setDocumentationType(DocumentationTypeMode documentationType) { this.documentationType = documentationType; } public String getBasePackage() { return basePackage; } public void setBasePackage(String basePackage) { this.basePackage = basePackage; } public SwaggerApiInfo getApiInfo() { return apiInfo; } public void setApiInfo(SwaggerApiInfo apiInfo) { this.apiInfo = apiInfo; } } //Document information contact entity class public static class SwaggerApiInfoContact { private String name; private String url; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } //Document information contact entity class public static class SwaggerApiInfo { private String title; private String description; @NestedConfigurationProperty private SwaggerApiInfoContact contact; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public SwaggerApiInfoContact getContact() { return contact; } public void setContact(SwaggerApiInfoContact contact) { this.contact = contact; } } //Input parameters through production interface private List<RequestParameter> getGlobalRequestParameters() { List<RequestParameter> parameters = new ArrayList<>(); parameters.add(new RequestParameterBuilder() .name("appid") .description("platform id") .required(true) .in(ParameterType.QUERY) .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))) .required(false) .build()); parameters.add(new RequestParameterBuilder() .name("udid") .description("Unique of the device id") .required(true) .in(ParameterType.QUERY) .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))) .required(false) .build()); parameters.add(new RequestParameterBuilder() .name("version") .description("Version number of the client") .required(true) .in(ParameterType.QUERY) .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))) .required(false) .build()); return parameters; } //Generate general response information private List<Response> getGlobalResonseMessage() { List<Response> responseList = new ArrayList<>(); responseList.add(new ResponseBuilder() .code("404") .description("Resource not found") .build()); responseList.add(new ResponseBuilder() .code("0") .description("success") .build()); responseList.add(new ResponseBuilder() .code("10") .description("System exception") .build()); responseList.add(new ResponseBuilder() .code("20") .description("Parameter error") .build()); responseList.add(new ResponseBuilder() .code("30") .description("System exception") .build()); //Or by enumerating classes // for (ResponseStatusEnum value:ResponseStatusEnum.values()) { // String code = String.valueOf(value.getCode()); // String message =value.getMessage(); // responseList.add(new ResponseBuilder().code(code).description(message); // } return responseList; } }
4. Write the Ctronller class
package com.example.demo.db.controller; import com.example.demo.db.domain.Student; import io.swagger.annotations.*; import org.springframework.web.bind.annotation.*; @Api(tags = "Student information Controller") @RestController @RequestMapping(value = "/Student",method = RequestMethod.GET) public class StudentController{ @ApiOperation(value ="Student information query findAllStudent Interface",notes = "Note: the interface passes id Get user details, id Must pass") @ApiImplicitParams({ @ApiImplicitParam(name = "sid", value = "user id", required = true, dataType = "String", paramType = "query",defaultValue = "01"), @ApiImplicitParam(name = "sname", value = "User name", required = false, dataType = "String", paramType = "query",defaultValue = "Lei Zhao"), }) @RequestMapping(value = "/findAllStudent") public Student findAllStudent(String sid,String sname){ return null; } }
5. Start access address:
http://localhost:8011/doc.html (add the access path that UI optimization depends on)
http://localhost:8011/swagger-ui/index.html (original path)
6. Swagger3 common notes
@Api: used on the requested class to describe the function of the class
Parameters:
tags: describe the function of this class
value: this parameter has no meaning and needs no configuration
@Api(tags = "Student information Controller")
@ApiOperation: used on the requested method to describe the function of the method
Parameters:
value: describes the function of the method
Notes: notes of the method
@ApiOperation(value ="Student information query findAllStudent Interface",notes = "Note: the interface passes id Get user details, id Must pass")
@ApiImplicitParams and @ ApiImplicitParam, and @ ApiParam
(1) @ ApiImplicitParams: used on the requested method and contains a set of parameter descriptions
(2) @ ApiImplicitParams: used in the @ ApiImplicitParams annotation to specify the configuration information of a request parameter
Parameters:
Name: parameter name
value: Chinese character description and explanation of the parameter
required: whether the parameter must be passed
paramType: where is the parameter placed
· header -- > acquisition of request parameters: @ RequestHeader
· query -- > acquisition of request parameters: @ RequestParam
· path (for restful interface) - > acquisition of request parameters: @ PathVariable
· body (not commonly used)
· form (not commonly used)
dataType: parameter type, default String, other values dataType="Integer"
defaultValue: the default value of the parameter
(3) @ ApiParam: used in method parameters to specify the configuration information of the corresponding request parameters
@ApiImplicitParams({ @ApiImplicitParam(name = "sid", value = "user id", required = true, dataType = "String", paramType = "query",defaultValue = "01"), @ApiImplicitParam(name = "sname", value = "User name", required = false, dataType = "String", paramType = "query",defaultValue = "Lei Zhao"), })
findAllStudent(@ApiParam(value = "id",name="id",required = true,defaultValue = "01") String id){
@ApiModel and @ ApiModelProperty
(1) @ ApiModel: used on the response class to represent a message that returns response data
(this is generally used in the scenario of @ RequestBody when creating a post,
Request parameters cannot be described with @ ApiImplicitParam annotation)
(2) @ ApiModelProperty: used on the property to describe the property of the response class
@ApiModel(value = "Student Entity class",description = "Student entity object") @Data public class Student implements Serializable { @ApiModelProperty("student id") private String sid; @ApiModelProperty("Student name") private String sname; @ApiModelProperty("Student age") private Date sage; @ApiModelProperty("Student gender") private String ssex; }
@ApiResponses and @ ApiResponse
(1) @ ApiResponses: used in the method of request, representing a group of responses
(2) @ ApiResponse: used in @ ApiResponses. It is generally used to express an incorrect response message
code: number, e.g. 400
message: information, such as "request parameters are not filled in"
response: the class that threw the exception
@ApiResponses({ @ApiResponse(code=400,message="Request parameters are not filled in"), @ApiResponse(code=404,message="There is no request path or the page Jump path is wrong") })