Swagger is an interface debugging tool, which can display the calling method, parameters, sub-modules of the interface friendly, display the interface very intuitively, and perform interface debugging, which plays a very good handover role in the front-end and back-end interactions.
1. Steps to use
1. Introduce related dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2. Write configuration class
package com.lyj.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//配置了swagger的Docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
//配置Swagger信息=apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact=new Contact("李大白","","1837383***@qq.com");
return new ApiInfo(
"李大白的SwaggerApi文档",
"世间永无bug",
"v1.0",
"",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
3. Use relevant annotations
After the Swagger environment is set up, you can use Swagger related comments
package com.example.demo.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/swagger")
@RestController //返回数据(不返回页面)注解
@Api(tags = {"swagger测试模块"}) //模块注解,在Swagger页面上这个类的接口内聚成单独模块
public class test {
@GetMapping("/test")
@ApiOperation("接口1") //接口名注解
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "测试接收id",dataType = "Long",example = "1"),
}) //用于Swagger页面介绍参数
public String hello(@RequestParam(value = "id",required = true) Long id){
return "Get请求方式 "+id;
}
}
4. Visit the Swagger page
Open the browser, enter your own path plus swagger-ui.html (the higher version is swagger-ui/index.html)
This is loclhost:8080/swagger-ui.html
5. Debug interface
Summarize
In the front-end and back-end separation projects, after the back-end project integrates Swagger, the front-end personnel can call the interface very well, and the joint debugging is also very intuitive, which greatly improves the efficiency of front-end and back-end interaction.