首先项目使用SpringBoot框架,swagger接口文档,下面上代码,从新建一个项目开始搭起。
参考文档:
swagger文档
Swagger注解说明
knife4j 参考文档
新建SpringBoot项目
POM文件配置
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.cn.binglong</groupId>
<artifactId>SwaggerDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
控制层
package com.cn.binglong.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 类 名: HelloController
* 描 述:
* 作 者: binglong180
* 创 建: 2020-07-07 14:40
* 邮 箱: binglong172@163.com
*/
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
启动类
package com.cn.binglong;
import com.cn.binglong.bean.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Arrays;
/**
* 类 名: TestMain
* 描 述:
* 作 者: binglong180
* 创 建: 2020-07-06 15:57
* 邮 箱: binglong172@163.com
*/
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
启动项目
引入Swagger pom 文件
<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>
创建SwaggerConfig 配置Swagger
host 修改request ip或域名
pathMapping 修改 request url
package com.cn.binglong.cfg;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 类 名: SwaggerConfig
* 描 述:
* 作 者: binglong180
* 创 建: 2020-07-08 12:22
* 邮 箱: binglong172@163.com
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost:8080")
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.cn.binglong.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("9.0")
.contact(new Contact("binglong180","www.binglong180.com","binglong172@163.com"))
.license("Swagger文档")
.licenseUrl("https://swagger.io/docs/specification/2-0/basic-structure/")
.build());
}
}
控制层多包扫描
package com.cn.binglong.cfg;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 类 名: SwaggerConfig
* 描 述:
* 作 者: binglong180
* 创 建: 2020-07-08 12:22
* 邮 箱: binglong172@163.com
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// 定义分隔符
private static final String splitor = ";";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost:8080")
.pathMapping("/")
.select()
/* .apis(RequestHandlerSelectors.basePackage("com.cn.binglong.controller"))*/
.apis(basePackage("com.cn.binglong.controller"
+ splitor +
"com.cn.binglong.controller2"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("9.0")
.contact(new Contact("binglong180","www.binglong180.com","binglong172@163.com"))
.license("Swagger文档")
.licenseUrl("https://swagger.io/docs/specification/2-0/basic-structure/")
.build());
}
public static Predicate<RequestHandler> basePackage(final String basePackage) {
return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
}
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
return input -> {
// 循环判断匹配
for (String strPackage : basePackage.split(splitor)) {
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
if (isMatch) {
return true;
}
}
return false;
};
}
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
}
Swagger注解说明
@Api:用在请求的类上,表示对类的说明
tags="说明该类的作用,可以在UI界面上看到的注解"
value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
@ApiOperation:用在请求的方法上,说明方法的用途、作用
value="说明方法的用途、作用"
notes="方法的备注说明"
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
@ApiResponses:用在请求的方法上,表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:用在属性上,描述响应类的属性
访问Swagger
http://localhost:8080/swagger-ui.html#/
加入Swagger 效果
不同环境下Swagger启用禁用
使用@Profile({}) 把相应的环境配置加入就表示在该环境下启用swagger,否则将会被禁用
@Configuration
@EnableSwagger2
@Profile({"dev"})
public class SwaggerConfig {
// 定义分隔符
private static final String splitor = ";";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost:8080")
.pathMapping("/")
.select()
/* .apis(RequestHandlerSelectors.basePackage("com.cn.binglong.controller"))*/
.apis(basePackage("com.cn.binglong.controller"
/* + splitor +
"com.cn.binglong.controller2"*/))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("1.0")
.contact(new Contact("binglong180","www.binglong180.com","binglong172@163.com"))
.license("Swagger文档")
.licenseUrl("https://swagger.io/docs/specification/2-0/basic-structure/")
.build());
}
Security 中整合swagger或其他安全中要对相应路径及资源放行
web.ignoring().antMatchers("/swagger/**")
.antMatchers("/swagger-ui.html")
.antMatchers("/webjars/**")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
整合 Knife4j pom文件加入
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
访问http://localhost:8080/doc.html
注意事项
- knife4j 参考文档 https://doc.xiaominfo.com/
- 安全框架要放行 springSecurity 或 shiro
web.ignoring().antMatchers("/swagger/**")
.antMatchers("/swagger-ui.html")
.antMatchers("/webjars/**")
.antMatchers("/v2/**")
.antMatchers("/v2/api-docs-ext/**")
.antMatchers("/swagger-resources/**")
.antMatchers("/doc.html");
/doc.html 和 /v2/api-docs-ext 是Knife4j 的其他是swagger的
- 配置 swagger knife4j 访问静态资源路径
@Configuration
public class SwaggerWebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}