1. 打开浏览器,访问:https://start.spring.io/
2. 根据页面提示,选择构建工具,开发语言,项目信息等。
- 使用IDE导入项目
添加相关依赖
添加 Maven 相关依赖,这里需要添加上WEB和SWAGGER依赖。
WEB依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
swagger依赖,这里选择 2.9.2 版本。
<!-- swagger -->
<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>
添加配置类
添加一个swagger 配置类,在工程下新建 config 包并添加一个 SwaggerConfig 配置类。
SwaggerConfig.java
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.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Kitty API Doc")
.description("This is a restful api document of Kitty.")
.version("1.0")
.build();
}
}
添加控制器
添加一个控制器,在工程下新建 controller包并添加一个 HelloController控制器。
HelloController.java
package com.louis.springboot.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/* 类注解 */
@Api(value = "desc of class")
@RestController
public class HelloController {
/* 方法注解 */
@ApiOperation(value = "desc of method", notes = "")
@GetMapping(value="/hello")
public Object hello( /* 参数注解 */ @ApiParam(value = "desc of param" , required=true ) @RequestParam String name) {
return "Hello " + name + "!";
}
}
运行项目启动
如遇错误:
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
两种解决方案任选其一:
- 参考地址
SpringFox3 Failed to start bean 'documentationPluginsBootstrapper' - 简书
SpringBoot更新至2.6.0,引发了这个bug。
在配置文件里加一条spring.mvc.pathmatch.matching-strategy=ant_path_matcher
可解决
- 参考地址:
打开浏览器,访问:http://localhost:8080/swagger-ui.html,进入swagger接口文档界面。
展开hello-controller的hello接口,输入参数并点击执行,就可以看到接口测试结果了。