What is the most annoying thing about development? When you think wholeheartedly of time, front end smiling of come over: “eldest brother, you didn’t tell me should pass what parameter!” . And blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah, blah. Didi di, wechat message: “how the interface is not ah, you are not the code to write a problem ah?” After a meal operation, board the console, log a look. Ah ~ (we do the groundhog bark together) the inside is broken… Parameter missing, parameter type wrong, wrong format, all kinds of. At this time very want to throw a document to the front end: you see! However, writing documents is really too much trouble, lazy… Had to go to the forum, Baidu Google under what to generate online document tools, the results as you wish, really have. Today, let’s go through spring Boot to integrate Swagger into online documentation. (Hoo ~~ cool, I feel like using this, you can not be the front end of the big guy “harassment”). Here are two ways to integrate Swagger. 5 minutes of programming, 2 hours of bullshit, and a whole day lost.

Without Starter

New project, POM file plus two Swagger necessary dependencies.

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

Swagger profile

@configuration @enablesWagger2 Public Class SwaggerConfig {/** * Swagger indicates that this interface generates documentation, including interface name, request method, parameters, return information, etc. * * @return * @API: Modifies the entire class and describes the function of Controller * @apiOperation: describes a method of a class, or an interface * @APIParam: describes a single parameter * @APIModel: * @apiResponse: one of the descriptions of the HTTP response * @apiResponses: the whole description of the HTTP response * @APIIgnore: Use this annotation to ignore the API * @APIError: information returned from an error * @APIIMPLICITParam: a request parameter * @ApiIMPLICITParams: */ @bean public Docket createRestApi() {start*/ ParameterBuilder tokenPar = new ParameterBuilder(); List<Parameter> pars = new ArrayList<Parameter>(); TokenPar. Name (" authorization "). The description (" token "). The modelRef (new ModelRef("string")).parameterType("header").required(false).build(); pars.add(tokenPar.build()); / / add the head end return new Docket (DocumentationType. SWAGGER_2). GroupName (" com. Developlee. HangZhou, ZheJiang "). The select () Apis (RequestHandlerSelectors. WithMethodAnnotation (ApiOperation. Class)) / / have the annotation doc Apis (RequestHandlerSelectors. BasePackage (com. Developlee. "swagger")) / / to modify for your own package path. The paths (PathSelectors. Any ()). The build ()  .globalOperationParameters(pars) //set Header .apiInfo(apiInfo()); } private ApiInfo ApiInfo () {return new ApiInfoBuilder().title("DevelopLee's Swagger online documentation ") .description(" Swagger documentation is strong!" ). TermsOfServiceUrl (" http://github.com/developlee "). The version (" 1.0 "). The build (); }}Copy the code

Write a Controller class test

@restController Public class UserController {@getMapping ("/userInfo") @apiOperation (notes = "Get user information ", value = "get user info") public String getUserInfo(){ return "getUserInfo"; } @postmapping ("/addUser") @apiOperation (notes = "add user info", value = "add user info") @apiimplicitParam (value = "Add user ", name = "add user", dataType = "java.lang.String", required = true) public String addUser(String str){ return "addUser"; }}Copy the code

Start the project… Access localhost:8080/swagger-ui.html (I drop a tortoise tortoise, this is ok?) (In fact, I went to talk to them. Feel the benefits this document brings to backend developers, especially lazy developers like all of you in this room.)

With swagger-spring-boot-starter

Here’s a great tool, swagger-Spring-boot-starter, from the spring4all.com community. Next we will use this dependency package to develop the Swagger document. Pom. XML dependency

<dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> < version > 1.7.1. RELEASE < / version > < / dependency >Copy the code

@enablesWagger2doc Opens the document

@SpringBootApplication @EnableSwagger2Doc public class SwaggerStarterApplication { public static void main(String[] args) { SpringApplication.run(SwaggerStarterApplication.class, args); }}Copy the code

Configuration example:

swagger.enabled=true swagger.title=spring-boot-starter-swagger swagger.description=Starter for swagger 2.x Swagger. Version = 1.7.1. RELEASE swagger. License = Apache license, Version 2.0 swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger swagger.contact.name=developlee swagger.contact.url=http://github.com/developlee [email protected] swagger.base-package=com.developlee swagger.base-path=/** swagger.exclude-path=/error, /ops/** swagger.globalOperationParameters[0].name=name one swagger.globalOperationParameters[0].description=some description one swagger.globalOperationParameters[0].modelRef=string swagger.globalOperationParameters[0].parameterType=header swagger.globalOperationParameters[0].required=true swagger.globalOperationParameters[1].name=name two swagger.globalOperationParameters[1].description=some description two  swagger.globalOperationParameters[1].modelRef=string swagger.globalOperationParameters[1].parameterType=body Swagger. GlobalOperationParameters [1]. The required = false / / cancel using default predefined response message, and use a custom response message swagger.apply-default-response-messages=false swagger.global-response-message.get[0].code=401 swagger.global-response-message.get[0].message=401get swagger.global-response-message.get[1].code=500 swagger.global-response-message.get[1].message=500get swagger.global-response-message.get[1].modelRef=ERROR swagger.global-response-message.post[0].code=500 swagger.global-response-message.post[0].message=500post swagger.global-response-message.post[0].modelRef=ERRORCopy the code

Configuration Description – Default configuration

- Swagger. Enabled = Whether to enable swagger. Default: True - swagger.title= Title - Swagger. description= Description - Swagger. version= version - Swagger. license= License - Swagger. licenseUrl= License URL - swagger. TermsOfServiceUrl = URL - swagger. Terms of service. Contact name = maintenance people - swagger. Contact the URL = URL - maintenance people Swagger.contact. email= Maintainer email-swagger. base-package= Base package of swagger scan. Default: full scan - swagger.base-path= Base URL rules to be processed. /** -swagger. Exclude-path = URL rule to exclude. Default: empty -swagger. Empty - swagger. GlobalOperationParameters [0]. Name = parameter name - swagger. GlobalOperationParameters [0]. The description = description information - Swagger. GlobalOperationParameters [0]. ModelRef = parameterized types - Swagger. GlobalOperationParameters [0]. ParameterType = location specified argument and an optional header, query, path, the body. The form - Swagger. GlobalOperationParameters [0]. Required = whether specified argument will preach, true, falseCopy the code

The Path is set

management.context-path=/ops

swagger.base-path=/**
swagger.exclude-path=/ops/**, /errorCopy the code

The above Settings resolve all request paths except /ops/ start and spring Boot /error.

Exclude-path can be used with the context-path of the spring boot actuator set as management. Context-path =/ OPS to exclude all monitoring endpoints.

Group configuration

<name>. Title = title - Swagger.docket.<name>. Description = Description - Swagger.docket.<name> Swagger.docket.<name>. License = License - Swagger.docket.<name>. LicenseUrl = License URL - Swagger.docket.<name>.termsofserviceurl = termsOfServiceUrl - swagger.docket.<name>.contact. Name = maintainer - Swagger.docket.<name>.contact.url= Maintainer URL - swagger.docket.<name>.contact.email= Maintainer email - Swagger.docket.<name>. Base-package = Base package for swagger scanning, default: full scan - swagger.docket.<name>. Base-path = Base URL rules to be processed, default: /** -swagger.docket.<name>. Exclude -path= exclude URL rule, default: <name>. Name = Parameter name - Swagger.docket.<name>. ModelRef = Specifies the parameter type - Swagger. Docket. < name >. ParameterType = location specified parameters, the optional header, query, path, the body. The form - Swagger.docket.<name>. Required =true True, false, swagger. Docket. < name >. GlobalOperationParameters [0]. Name = parameter name - Swagger. Docket. < name >. GlobalOperationParameters [0]. The description = description information - Swagger. Docket. < name >. GlobalOperationParameters [0]. ModelRef = location specified parameters, the optional header, query, path, the body. The form - Swagger. Docket. < name >. GlobalOperationParameters [0]. ParameterType = whether specified argument will preach, true, falseCopy the code

Go to Github.com for more.

Finally, the above sample code is available in mygithub.comFound.

My personal public account: Developlee chic life.

Attention is not necessarily updated, the update can not be.