Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
这里我给大家带来一个简单的整合DEMO 先来看项目结构
下面是基本的步骤
一.添加MAVEN依赖
- <dependency>
 - <groupId>io.springfox</groupId>
 - <artifactId>springfox-swagger2</artifactId>
 - <version>2.2.2</version>
 - </dependency>
 - <dependency>
 - <groupId>io.springfox</groupId>
 - <artifactId>springfox-swagger-ui</artifactId>
 - <version>2.2.2</version>
 - </dependency>
 - <dependency>
 - <groupId>org.codehaus.jackson</groupId>
 - <artifactId>jackson-core-asl</artifactId>
 - <version>1.9.13</version>
 - </dependency>
 
二.编写Swagger配置类
- @Configuration
 - @EnableSwagger2
 - public class Swaggers {
 - @Bean
 - public Docket swaggerSpringMvcPlugin() {
 - ApiInfo apiInfo = new ApiInfo("sample of springboot", "sample of springboot", null, null, null, null, null);
 - Docket docket = new Docket(DocumentationType.SWAGGER_2).select().paths(regex("/user/.*")).build()
 - .apiInfo(apiInfo).useDefaultResponseMessages(false);
 - return docket;
 - }
 - /*private ApiInfo apiInfo() {
 - return new ApiInfoBuilder().title("测试API")
 - .description("樊亚的测试API1")
 - .version("1.0.0")
 - .build();
 - }*/
 - /* @Bean
 - public Docket createRestApi() {
 - return new Docket(DocumentationType.SWAGGER_2)
 - .apiInfo(apiInfo())
 - .select()
 - .apis(RequestHandlerSelectors.basePackage("com.didispace.web"))
 - .paths(regex("/user/.*"))
 - .build();
 - }
 - */
 - }
 
当然也可以用链式编程的方法实现,这里我使用的是NEW
三.编写Controller
- @RestController
 - @RequestMapping("/user")
 - @Api(value = "Shop")
 - public class SpringBootController {
 - @ApiOperation(value = "获取helloWorld", notes = "简单SpringMVC请求")
 - @RequestMapping("/")
 - String home() {
 - return "HELLO WORLD";
 - }
 - @ApiOperation(value = "获得A+B", notes = "根据url的classNo和url的studentName获得请求参数的字符串相加,RestFul风格的请求")
 - @ApiImplicitParams({@ApiImplicitParam(name = "classNo", value = "班级编号", required = true, dataType = "String"),
 - })
 - @RequestMapping(value = "/class/{classNo}/to/{studentName}", method = RequestMethod.GET)
 - String world(@PathVariable("classNo") String classNo, @PathVariable("studentName") String studentName) {
 - return classNo + " " + studentName;
 - }
 - }
 
四.编写Application载入类
 
- @SpringBootApplication
 - public class Application {
 - public static void main(String[] args) {
 - SpringApplication.run(Application.class,args);
 - }
 - }
 
Swagger会默认把所有Controller中的RequestMapping方法都生成API出来,实际上我们一般只需要标准接口的(像返回页面的那种Controller方法我们并不需要),所有你可以按下面的方法来设定要生成API的方法的要求。
至此功能基本实现了,我们可以通过访问地址http://localhost:8080/swagger-ui.html/
查看生成好的API