This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Include a column

Spring Boot quick start

Java full stack Architect

preface

I believe that most developers have been tortured by interface documentation at some point or another. After the back-end personnel interface is developed, it takes a lot of effort to write and maintain the interface document, and it is often too late to update. Swagger is annotation-based and provides a flexible interface to document templates. After the update runs and compiles, you can preview it directly online, avoiding the problem of repeated modifications. Here’s a look at the Swagger UI.

What is Swagger UI

Swagger UI is a canonical and complete framework for generating, describing, invoking, and visualizing RESTful Web services. The main function is to automatically generate and preview the interface documents online, which can be used to test business functions.

The goal is to have the client and the file system update at the same rate as the server. The file’s methods, parameters, and models are tightly integrated into the server-side code, allowing the API to always be synchronized. Swagger makes deployment management and using a powerful API easier than ever.

Use of Swagger UI

Introduction of depend on

Maven importing required dependency packages. The details are as follows:

<! -- swagger start --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> The < version > 2.5.0 < / version > < / dependency > <! -- swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> The < version > 2.5.0 < / version > < / dependency > <! -- swagger end -->Copy the code

Swagger UI configuration class

The Swagger UI configuration class first provides a powerful constructor for creating aN API. The basic information of building API includes page title, version number, description of interface document, address of service terms, Contact, license information, license information address, etc., where contact can be other more information.

  • ApiInfo: Builds the detailed information function of the Api documentation.
  • Docket: API documentation information returned by the Swagger UI.

The main attributes are:

  • ApiInfo () is the basic information of the apiInfo.
  • Select ()Api selector generator.
  • Apis is the package path to the API document required by the current request handler selector.
  • Paths path selector for any handles any package.
public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) ApiInfo (apiInfo ()). The select () / / for the current package path. The apis (RequestHandlerSelectors. BasePackage (" com. Example. The demo ")) .paths(PathSelectors.any()) .build(); } private ApiInfo ApiInfo () {return new ApiInfoBuilder().title("Spring Boot uses Swagger2 to build RESTful apis ").contact(new) Contact (" Bryan ", "http://blog.bianxh.top/", "")) version (" 1.0"). The description (" API description "). The build (); }Copy the code

Swagger UI annotations

  • @api: Used on a class to explain what that class does.
  • ApiOperation: Annotation to add method description to API.
  • ApiImplicitParams: Used to include a set of parameters on a method.
  • ApiImplicitParam: Used to annotate method input parameters.

Common parameters:

Header: Put the Request parameters in the Request header, and use @requestheader to get query: put the Request parameters in the Request address, and use @requestparam to get path: (for a restful interface) - > request parameter acquisition: @ PathVariable body: (not used) form (not used) name: parameter name dataType: parameter types required: whether parameters must pass (true | false) value: Parameter meaning defaultValue: indicates the defaultValue of the parameterCopy the code
  • @apiresponses: Used to indicate a set of responses

  • @apiResponse: Used in @apiResponses, typically to express an incorrect response message. ApiResponse contains three attributes

Message: indicates the information, such as "the request succeeded". Response: indicates the data returned after the request succeededCopy the code
  • ApiModel: Information that describes a Model (usually used when request parameters cannot be described using the @ApiImplicitParam annotation)

  • ApiModelProperty: Describes the property of a Model

The source code

pom.xml

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.3.0. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>swagger</artifactId> <version>0.0.1 -snapshot </version> <name>swagger</name> <description>Demo project for Spring Boot and MyBatis and Swagger</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <! -- commons start --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> The < artifactId > Commons - lang3 < / artifactId > < version > 3.7 < / version > < / dependency > <! -- commons end --> <! -- mybatis start--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <! -- mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.1 < / version > < / dependency > <! -- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId> <version>1.1.11</version> </dependency> <! -- mybatis end--> <! --junit start --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <! < <groupId> <groupId> <artifactId> <version>4.12</version> <scope>test</scope> </dependency> <! --junit end --> <! -- swagger start --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> The < version > 2.5.0 < / version > < / dependency > <! -- swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> The < version > 2.5.0 < / version > < / dependency > <! -- swagger end --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code

application.properties

Server. The port = 8888 # mysql spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / test? useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull spring.datasource.username=test spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource mybatis.mapper-locations=classpath*:mapper/**/*.xmlCopy the code

SwaggerConfig

package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @ClassName SwaggerConfig * @Description: SwaggerConfig config * @author JavaZhan @public id :Java full stack Architect * @date 2020/6/13 * @version V1.0 **/ @configuration @enableswagger2 Public class SwaggerConfig {/** * @classname create Docket * @description: Public Docket createRestApi() {Docket * @author JavaZhan * @date 2020/6/13 * @version V1.0 **/ @bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } /** * @ClassName ApiInfo * @Description: ApiInfo * @author JavaZhan @public id: JavaZhan * @date 2020/6/13 * @version V1.0 **/ private ApiInfo ApiInfo () {return new ApiInfoBuilder (). The title (" Denver authors Little ajie "). Contact (new contact (" little ajie ", "https://juejin.cn/user/2040300414187416/posts", "").version("1.0").description(" public id: Java full stack Architect API description ").build(); }}Copy the code

DemoSwaggerApplication

package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @className Swagger UI Integration test * @description: Swagger UI integration Test bootstrap class * @author JavaZhan @public id :Java Full stack Architect * @date 2020/6/13 * @version V1.0 **/ @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoSwaggerApplication { public static void main(String[] args) { SpringApplication.run(DemoSwaggerApplication.class, args); }}Copy the code

UserController

package com.example.demo.controller; import com.example.demo.module.User; import com.example.demo.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.List; /** * @ClassName UserController * @Description: User admin * @author JavaZhan @public :Java full stack Architect * @date 2020/6/13 * @version V1.0 **/ @api (description = "user admin ") @RequestMapping("user") @Controller public class UserController { @Resource private UserService userService; @requestMapping (Value = "getAllUser",method = requestMethod.get) @responseBody public List<User> getAllUser(){ return userService.getAllUser(); }}Copy the code

Use the Swagger UI

Open API

In the browser type:http://localhost:8888/swagger-ui.htmlThe interface document information below appears, indicating that the Swagger document has been integrated successfully:

The test interface

Select the user/getAllUser interface to obtain all user information. You can see that the request mode is GET request. The request parameter is null, and the Model returned is User,Click Try it out. The interface automatically requests requests and returns request parameters and returned value information. Request succeeded, return status 200. Normal List data is displayed.

conclusion

So Swagger and Spring Boot integration works. You can delve deeper into Swagger information, and you’re sure to find new discoveries.

Author introduction: [little ajie] a love to tinker with the program ape, JAVA developers and enthusiasts. Public account [Java full stack architect] maintainer, welcome to pay attention to reading communication.

Well, thank you for reading, I hope you like it, if it helps you, welcome to like the collection. If there are any shortcomings, please comment and correct them. See you next time.

Recommended Reading:

My first Spring Boot project is up!

Spring Boot column was set up over the weekend. Welcome to learn and communicate

Spring Boot integrates MyBatis and connects to the database.

【Spring Boot Quick Start 】 four, Spring Boot integration JUnit