<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>
package com.cesmart; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan(basePackages = "com.cesmart") // scan those packages for beans.@ComponentScan({"com.teradata.notification","com.teradata.dal"}) //@EnableSwagger2 //Start swagger annotation public class Application { public static void main(String[] args) { ApplicationContext applicationContext = SpringApplication.run(Application.class, args); } }
package com.cesmart.entity; public class TestModel { private String name; // private String value; // public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "TestModel [name=" + name + ", value=" + value + "]"; } }
package com.cesmart.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.base.Predicates; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration//Defined as the configuration file of spring boot @EnableSwagger2//Start swagger annotation public class Swagger2 { public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.cesmart.controller"; @Bean(value="createRestApi") public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .groupName("test1") .pathMapping("/") .apiInfo (apiInfo ()) .select() .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) .paths(Predicates.or(PathSelectors.regex("/webTest2/.*"))) .build(); //groupName, group name //pathMapping, mapping path (will be added to the front of the URL to form a new path, such as: "/xing/WebTest/webTest",(pathMapping("/xing"))) //apiInfo, API information description //select, selecting those paths and api will generate document //apis, scan those packages, RequestHandlerSelectors.any() means to monitor all apis //paths, match those paths, PathSelectors.any() means all paths, } @Bean(value="createRestApi2") public Docket createRestApi2() { return new Docket(DocumentationType.SWAGGER_2) .groupName("test2") .pathMapping("/") .apiInfo (apiInfo2 ()) .select() .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) .paths(Predicates.or(PathSelectors.regex("/webTest/.*"))) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Building RESTful APIs with Swagger2 in Spring Boot") .description("For more Spring Boot related articles, please pay attention: http://blog.didispace.com/") .termsOfServiceUrl("http://blog.didispace2.com/") .contact("Program Ape DD") .version("1.0") .license("license") .licenseUrl("licenseUrl") .build(); //title, title, displayed at the top of the page //description, description, displayed at the top of the page //termsOfServiceUrl, //contact, showing "Created by + contact", at the top of the page //version, API version, displayed at the top of the page //license, copyright } private ApiInfo apiInfo2() { return new ApiInfoBuilder() .title("Building RESTful APIs with Swagger2 in Spring Boot") .description("For more Spring Boot related articles, please pay attention: http://blog.didispace.com/") .termsOfServiceUrl("http://blog.didispace2.com/") .contact("Program Ape DD") .version("1.0") .license("license") .licenseUrl("licenseUrl") .build(); } }
package com.cesmart.controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cesmart.entity.TestModel; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @Api(value = "WebTest", description = "About Swagger2 operations") @RequestMapping(value = "/webTest") // Used on a class to describe the role of the class // value, the description to display in the class // description, the description in the class // Display form: "value: description", as shown above as "WebTest: about Swagger2 operations" public class WebTest { @ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) // used in the method to explain the function of the method // Displayed in the method description, showing notes // response, the interface returns the parameter type // value = "Interface Description", // notes = "Interface Release Notes" @ApiImplicitParams({ @ApiImplicitParam(paramType = "path", required = true, name = "test", dataType = "String", value = "456"), @ApiImplicitParam(paramType = "path", required = true, name = "test2", dataType = "String", value = "789") }) // @ApiImplicitParam, represents the description of a parameter, which is related to the request parameter // paramType, where to put the parameter // required, whether the parameter must be passed // name, parameter name // dataType, parameter type (description) // value, the meaning of the parameter (description) @ApiParam @RequestMapping(value = "/webTest/{test}/{test2}", produces = "text/plain;charset=UTF-8", method = RequestMethod.GET) public String webTest(@PathVariable("test") String test, @PathVariable("test2") String test2) { System.out.println("webTest"); System.out.println("test == " + test); System.out.println("test2 == " + test2); return "webTest"; } @ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", required = true, name = "test", dataType = "String", value = "456"), @ApiImplicitParam(paramType = "query", required = true, name = "test2", dataType = "String", value = "789") }) @RequestMapping(value = "/webTest2", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST) public String webTest2(String test, String test2) { System.out.println("webTest"); System.out.println("test == " + test); System.out.println("test2 == " + test2); return "webTest"; } @ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", required = true, name = "name", dataType = "String", value = "456"), @ApiImplicitParam(paramType = "query", required = true, name = "value", dataType = "String", value = "789") }) @RequestMapping(value = "/webTest3", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST) public String webTest3(@ModelAttribute TestModel testModel) { // Use @ModelAttribute here so that the testModel input box will not appear System.out.println("testModel == " + testModel.toString()); return "webTest"; } }
package com.cesmart.controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cesmart.entity.TestModel; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @Api(value = "WebTest", description = "About Swagger2 operation",,tags="Device online duration statistics interface") @RequestMapping(value = "/webTest2") // Used on a class to describe the role of the class // value, the description to display in the class // description, the description in the class // Display form: "value: description", as shown above as "WebTest: about Swagger2 operations" public class WebTest2 { @ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) // used in the method to explain the function of the method // Displayed in the method description, showing notes // response, the interface returns the parameter type // value = "Interface Description", // notes = "Interface Release Notes" @ApiImplicitParams({ @ApiImplicitParam(paramType = "path", required = true, name = "test", dataType = "String", value = "456"), @ApiImplicitParam(paramType = "path", required = true, name = "test2", dataType = "String", value = "789") }) // @ApiImplicitParam, represents the description of a parameter, which is related to the request parameter // paramType, where to put the parameter // required, whether the parameter must be passed // name, parameter name // dataType, parameter type (description) // value, the meaning of the parameter (description) @ApiParam @RequestMapping(value = "/webTest/{test}/{test2}", produces = "text/plain;charset=UTF-8", method = RequestMethod.GET) public String webTest(@PathVariable("test") String test, @PathVariable("test2") String test2) { System.out.println("webTest"); System.out.println("test == " + test); System.out.println("test2 == " + test2); return "webTest"; } @ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", required = true, name = "test", dataType = "String", value = "456"), @ApiImplicitParam(paramType = "query", required = true, name = "test2", dataType = "String", value = "789") }) @RequestMapping(value = "/webTest2", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST) public String webTest2(String test, String test2) { System.out.println("webTest"); System.out.println("test == " + test); System.out.println("test2 == " + test2); return "webTest"; } @ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", required = true, name = "name", dataType = "String", value = "456"), @ApiImplicitParam(paramType = "query", required = true, name = "value", dataType = "String", value = "789") }) @RequestMapping(value = "/webTest3", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST) public String webTest3(@ModelAttribute TestModel testModel) { // Use @ModelAttribute here so that the testModel input box will not appear System.out.println("testModel == " + testModel.toString()); return "webTest"; } }
illustrate: @Api: used on a class to describe the role of the class @ApiOperation: used on the method to explain the function of the method @ApiImplicitParams: used on a method to contain a set of parameter descriptions @ApiImplicitParam: used in the @ApiImplicitParams annotation to specify various aspects of a request parameter paramType: where to put the parameter Header-->Getting request parameters: @RequestHeader query-->Getting request parameters: @RequestParam path (for restful interface) --> get request parameters: @PathVariable body (not commonly used) form (not commonly used) name: parameter name dataType: parameter type required: whether the parameter must be passed value: the meaning of the parameter defaultValue: the default value of the parameter @ApiResponses: used to represent a set of responses @ApiResponse: used in @ApiResponses, generally used to express a wrong response information code: number, such as 400 message: information, such as "request parameters are not filled in" response: the class that throws the exception @ApiModel: Describes the information of a Model (this is generally used when creating a post, in scenarios such as @RequestBody, when the request parameters cannot be described using the @ApiImplicitParam annotation) @ApiModelProperty: describes the properties of a model
Open locally: http://localhost:8080/swagger-ui.html
date using format input annotation
public String getDeviceOnlineTimeByYearMonth2(String deviceType, String modelNo, String deviceId, int groupType, @DateTimeFormat(pattern = "yyyyMMdd") Date startDate, @DateTimeFormat(pattern = "yyyyMMdd") Date endDate) {
It can also be done by using the model at the interface, and the relevant parameter settings are set in the model.
public class ParamModel { private Long id; private String nameId; @ApiModelProperty(required = true, dataType = "int", value = "1235", name = "xing") private Integer age; @ApiModelProperty(required = true, dataType = "date", value = "时间(yyyyMMdd)") @ApiParam(defaultValue = "20170213") @DateTimeFormat(pattern = "yyyyMMdd") private Date time; }
If you don't write @ApiImplicitParams at the interface, it will also be recognized, but it will allow you to process more parameters and
increase public parameters
class SwaggerConfiguration { @Bean public Docket createRestApi() { ParameterBuilder builder = new ParameterBuilder(); Parameter parameter = builder .parameterType("query") //parameter type supports header, cookie, body, query etc .name("access_token") //Parameter name .description("Please enter your Access Token") .modelRef(new ModelRef("string"))//Specify the type of parameter value .required(false) .build(); List<Parameter> parameters = Lists.newArrayList(parameter); return new Docket(DocumentationType.SWAGGER_2) .groupName("zlcloud-mkt-mfc-service") .pathMapping("/") .apiInfo (apiInfo ()) .select() .apis(RequestHandlerSelectors.basePackage("com.zlcloud.mfc.controller")) .paths(PathSelectors.any()) .build() .globalOperationParameters(parameters); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("[RESTful APIs]--zlcloud-mkt-mfc-service") .description("zlcloud-mkt-mfc-service module interface") .contact("ZL") .version("1.0") .build(); } }
Parameter passing using models
public AjaxResult findByStatus(@RequestBody SalesParameterModel salesParameterModel) @ApiModel @Table(name = "t_sell_goods") public class Goods implements Serializable { private static final long serialVersionUID = -8444776915480123879L; /** * Unique code */ @Id @ApiModelProperty(required = false, name = "goodsid", value = "唯一码",example="123456",position=1) private Long goodsid; }
@ApiOperation(value = "Interface Description", notes = "Interface Release Notes", response = String.class) @RequestMapping(value = "/test4", produces = "text/plain;charset=UTF-8", method = RequestMethod.POST) public String webTest4(@ApiParam(value="地址",defaultValue="123456") @RequestParam(required = true) String address) { System.out.println("dateTimeFormatTestModel == " + address.toString()); return "test3"; }
@JsonFormat
public class DateTimeFormatTestModel2 { @ApiModelProperty(required = false, name = "userId", value = "userId", example = "userId") private String userId; @ApiModelProperty(required = false, name = "date", value = "date yyyyMMdd", example = "20170809") @JsonFormat(pattern="yyyyMMdd",timezone="GMT+8") //It can be used for input and output, //in order to facilitate serialization and deserialization of date type fields //@DateTimeFormat(pattern = "yyyy-MM-dd") //yyyyMMdd in beans cannot be converted, but "yyyy-MM-dd" can, but it takes 8 hours private Date date; @ApiModelProperty(required = false, name = "name", value = "name", example = "name") private String name;
Reference text (use example): http://www.iteye.com/topic/1145103
Reference text (use example): http://www.open-open.com/lib/view/open1455546851058.html
Reference text (definition Multiple groups): http://blog.csdn.net/catoop/article/details/50668896
Reference text (example of use): http://www.jianshu.com/p/8033ef83a8ed
Reference text (annotation instructions (English) )): https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md
Refer to the original text (annotation usage instructions, usage examples): http://www.cnblogs.com/java-zhao /p/5348113.html
Reference text (annotation instructions (English)): https://github.com/swagger-api/swagger-core/wiki/Annotations
Reference text (official website): http://swagger.io/ specification/