swagger
官网
借助Swagger开源和专业工具集,为用户,团队和企业简化API开发。
依赖
在项目中使用Swagger需要springbox
- swagger2
- ui
Springboot 集成 Swagger
快速入门
-
新建springboot项目
-
mvnrepository.com仓库搜索 springfox-swagger,找到坐标 :Springfox Swagge UI、Springfox Swagger2
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
-
编写一个Hello工程
package com.kuang.swagger.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping(value = "/hello") public String hello() { return "hello"; } }
-
集成Swagger
package com.kuang.swagger.config; import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 //开启Swagger2 public class SwaggerConfig { }
配置Swagger
Swagger的bean实例 Docket;
package com.kuang.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.ArrayList;
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
//配置了swagger的Docket的Bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否启动swagger,如果为false,则swagger不能再浏览器中访问
.enable(false)
.select()
//扫描接口的方式
//basePackage 指定要扫描的包
//any():扫描全部
//none():不扫描
//withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象 HelloController.class
//withMethodAnnotation:扫描方法上的注解 GetMapping.class
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
.build();
}
//配置swagger信息= apiInfo
private ApiInfo apiInfo(){
Contact contact = new Contact("王超", "123", "123");
return new ApiInfo(
"howard的SwaggerAPI文档",
"作者是Howard",
"v1.0",
"http://abc1024.pub",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
配置文件
application.properties
spring.profiles.active=dev
application-dev.properties
server.port=8081
application-pro.properties
server.port=8082