一、Swagger简介
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。
二、创建项目
引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
修改启动类
添加注解
@EnableOpenApi
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication
@EnableOpenApi
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
创建Swagger配置类
import static springfox.documentation.service.ApiInfo.DEFAULT_CONTACT;
import java.util.ArrayList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author techoc
* @Date 2021/4/11
*/
@EnableOpenApi //开启swagger3
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30) //与swagger2.0不同
//开启swagger
.enable(true)
.groupName("swagger")
.apiInfo(apiInfo())
.select()
//设置扫描路径
.apis(RequestHandlerSelectors.basePackage("cn.techoc.swaggerdemo.controller"))
//指定扫描web路径
//.paths(PathSelectors.ant("/techoc/**"))
.build();
}
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("Techoc", "https://techoc.xyz", "[email protected]");
return new ApiInfo(
//文档标题
"Swagger-demo",
//文档描述
"学习Swagger的demo项目",
//文档版本
"2.0",
//组织链接
"https://techoc.xyz",
//连接点
contact,
//开源协议
"Apache 2.0",
//开源协议url
"https://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
}
创建Controller
package cn.techoc.swaggerdemo.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author techoc
* @Date 2021/4/11
*/
@RestController
@Api(tags = "用户管理")
public class HelloController {
@ApiOperation("返回id")
@RequestMapping(value = "/hello", method = RequestMethod.GET)
@ApiImplicitParam(name = "id", value = "用户编号", readOnly = true)
public int hello(@RequestParam(required = true) int id) {
return id + 2;
}
}
运行项目
标签:Swagger,使用,springframework,3.0,org,import,springfox,documentation From: https://www.cnblogs.com/techoc/p/17866095.html