创建项目
编写controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping(value = "/say")
public String sayHello(){
return "hello spring";
}
}
测试结果
1、浏览器访问:http://localhost:8080/say
2、输出显示:hello spring
生成定制化字符串——文字banner
在线工具:
1、http://www.patorjk.com/software/taag/
2、http://www.network-science.de/ascii/
_
| |
___ _ __ ___ __ _ _ __| |_ _ __ ___ ___ ___ _ __
/ __| '_ ` _ \ / _` | '__| __| | '_ ` _ \ / _ \ / _ \| '_ \
\__ \ | | | | | (_| | | | |_ | | | | | | (_) | (_) | | | |
|___/_| |_| |_|\__,_|_| \__| |_| |_| |_|\___/ \___/|_| |_|
配置
1、将上述字符串写入文件banner.txt
2、将文件存放在项目路径resource目录下即可
启动效果:
swagger3.0简介
Swagger 是一套基于 OpenAPI 规范(OpenAPI Specification,OAS)构建的开源工具,可以帮助我们设计、构建、记录以及使用 Rest API,可以将 Controller 的方法以文档的形式展现。
新特性:
- Remove explicit dependencies on springfox-swagger2
- Remove any
@EnableSwagger2
… annotations- Add the springfox-boot-starter dependency
- Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces.
引入配置
io.springfox
springfox-boot-starter
3.0.0
# application.yml配置文件
# 项目名称配置
spring:
application:
name: smart-moon
# 服务端口配置
server:
port: 8080
# swagger配置
swagger:
enable: true
application-name: ${spring.application.name}
application-version: 1.0
application-description: springfox swagger 3.0
try-host: http://localhost:${server.port}
测试用例
自定义配置加载类
@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {
/**
* 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
*/
private Boolean enable;
/**
* 项目应用名
*/
private String applicationName;
/**
* 项目版本信息
*/
private String applicationVersion;
/**
* 项目描述信息
*/
private String applicationDescription;
/**
* 接口调试地址
*/
private String tryHost;
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getApplicationVersion() {
return applicationVersion;
}
public void setApplicationVersion(String applicationVersion) {
this.applicationVersion = applicationVersion;
}
public String getApplicationDescription() {
return applicationDescription;
}
public void setApplicationDescription(String applicationDescription) {
this.applicationDescription = applicationDescription;
}
public String getTryHost() {
return tryHost;
}
public void setTryHost(String tryHost) {
this.tryHost = tryHost;
}
}
配置初始化,基于自定义配置类模板初始化完整swagger配置
@Configuration
public class SwaggerConfiguration implements WebMvcConfigurer {
private final SwaggerProperties swaggerProperties;
public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
this.swaggerProperties = swaggerProperties;
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30).pathMapping("/")
// 定义是否开启swagger,false为关闭,可以通过变量控制
.enable(swaggerProperties.getEnable())
// 将api的元信息设置为包含在json ResourceListing响应中。
.apiInfo(apiInfo())
// 接口调试地址
.host(swaggerProperties.getTryHost())
// 选择哪些接口作为swagger的doc发布
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
// 支持的通讯协议集合
.protocols(newHashSet("https", "http"))
// 授权信息设置,必要的header token等认证信息
.securitySchemes(securitySchemes())
// 授权信息全局应用
.securityContexts(securityContexts());
}
/**
* API 页面上半部分展示信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
.description(swaggerProperties.getApplicationDescription())
.contact(new Contact("swagger3.0", null, "[email protected]"))
.version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
.build();
}
/**
* 设置授权信息
*/
private List securitySchemes() {
ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
return Collections.singletonList(apiKey);
}
/**
* 授权信息全局应用
*/
private List securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
.build()
);
}
@SafeVarargs
private final Set newHashSet(T... ts) {
if (ts.length > 0) {
return new LinkedHashSet<>(Arrays.asList(ts));
}
return null;
}
/**
* 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息
*/
@SuppressWarnings("unchecked")
@Override
public void addInterceptors(InterceptorRegistry registry) {
try {
Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
List registrations = (List) ReflectionUtils.getField(registrationsField, registry);
if (registrations != null) {
for (InterceptorRegistration interceptorRegistration : registrations) {
interceptorRegistration
.excludePathPatterns("/swagger**/**")
.excludePathPatterns("/webjars/**")
.excludePathPatterns("/v3/**")
.excludePathPatterns("/doc.html");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
编写controller
@EnableOpenApi // 也可以不写此注解
@Api(tags="账户管理-swagger3.0")
@RestController
@RequestMapping("/admin/list/user")
public class MyController {
@ApiOperation(value = "账户列表")
@GetMapping
public List list(){
return List.of("张三","李四","爱丽丝");
}
@ApiOperation(value = "根据ID删除用户")
@DeleteMapping("{id}")
public boolean removeById(
@ApiParam(name = "id", value = "用户id", required = true)
@PathVariable String id){
return true;
}
}
效果:Swagger UI
Knife4j简介
Knife4j
的前身是swagger-bootstrap-ui
,前身swagger-bootstrap-ui
是一个纯swagger-ui
的ui
皮肤项目,Knife4j
不仅仅将前身的Ui皮肤通过Vue技术栈进行了重写,也增加了更多个性化的特性增强功能,基于springfox项目以及OpenAPI的规范,为用户提供了更加丰富的体验。
引入配置
com.github.xiaoymin
knife4j-spring-boot-starter
3.0.3
测试用例
1.创建Swagger配置依赖:
@Configuration
@EnableSwagger2
public class Knife4jConfiguration {
@Value("${swagger.enable}")
private Boolean enable;
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.enable(enable)
.apiInfo(
new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo restful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact(new Contact("管理员", "http://www.xx.com/", "[email protected]"))
.version("1.0")
.build()
)
//分组名称
.groupName("2.0版本")
.select()
//这里指定你自己的Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.example.smartmoon.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
2.编写controller实现一个简单的restful接口
@RestController
@RequestMapping(value = "/api/v2/user", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "用户管理")
public class UserController {
@GetMapping
@ApiOperation(value = "分页查询-1")
public String page(){
return "测试分页查询";
}
@GetMapping("/haha")
@ApiOperation(value = "分页查询-2")
public List getData(){
List list = new ArrayList<>();
list.add(new UserEntity().setName("花花").setSex("男"));
list.add(new UserEntity().setName("小王").setSex("女"));
return list;
}
}
@Data
@Accessors(chain = true)
@ApiModel
public class UserEntity {
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("性别")
private String sex;
}
3.运行效果