转自:http://www.leftso.com/blog/223.html
现在微服务已经有了很大的发展势头。微服务中常用的接口方式就是Restful风格,实际的REST规范并没有建议使用任何标准的方法来记录我们将要公开的REST api(就像SOAP的WSDL)。因此,每个人都在用自己的方式记录他们的api,这导致了通用结构上的一个缺陷,为了解决这个问题,出现了swagger,根据swagger生成的接口文档,所有人都可以很容易地理解并进行使用相应的接口。
我们将首先创建一些REST api接口,这些api接口将用于演示Swagger的文档功能。我们将使用Spring boot风格来显示rest API,以获得更快的开发时间。
1、创建spring boot项目
可以去spring boot官网创建一个web带Rest接口依赖的spring boot项目,也可以用idea工具创建。(如果)
2、修改application.properties配置文件。
添加以下属性。项目将会从 /swagger2-demo
context 路径启动应用.
3、添加一个REST的contrller和实体类
创建类Swagger2DemoRestController,他将会
为学生实体提供基本的基于REST的功能。
package com.testswagger.controller; import com.testswagger.model.Student; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author xmh * @description swagger2的controller * @Date 2020/1/7 */ @RestController public class Swagger2DemoRestController { Liststudents = new ArrayList (); { students.add(new Student("Sajal", "IV", "India")); students.add(new Student("Lokesh", "V", "India")); students.add(new Student("Kajal", "III", "USA")); students.add(new Student("Sukesh", "VI", "USA")); } @RequestMapping(value = "/getStudents") public List getStudents() { return students; } @RequestMapping(value = "/getStudent/{name}") public Student getStudent(@PathVariable(value = "name") String name) { return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); } @RequestMapping(value = "/getStudentByCountry/{country}") public List getStudentByCountry(@PathVariable(value = "country") String country) { System.out.println("Searching Student in country : " + country); List studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)) .collect(Collectors.toList()); System.out.println(studentsByCountry); return studentsByCountry; } @RequestMapping(value = "/getStudentByClass/{cls}") public List getStudentByClass(@PathVariable(value = "cls") String cls) { return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList()); } }
Student.java
package com.testswagger.model; /** * @author xmh * @description Student实体类 * @Date 2020/1/7 */ public class Student { private String name; private String cls; private String country; public Student(String name, String cls, String country) { super(); this.name = name; this.cls = cls; this.country = country; } public String getName() { return name; } public String getCls() { return cls; } public String getCountry() { return country; } @Override public String toString() { return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]"; } }
4、配置Swagger
添加Swagger的maven依赖库
io.springfox springfox-swagger2 2.6.1 io.springfox springfox-swagger-ui 2.6.1
5、添加Swagger配置类
package com.testswagger.controller; import com.google.common.base.Predicates; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author xmh * @description Swagger2配置 * @Date 2020/1/7 */ @Configuration @EnableSwagger2 public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter { @Bean public Docket api() { // @formatter:off //Register the controllers to swagger //Also it is configuring the Swagger Docket return new Docket(DocumentationType.SWAGGER_2).select() // .apis(RequestHandlerSelectors.any()) .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))) // .paths(PathSelectors.any()) // .paths(PathSelectors.ant("/swagger2-demo")) .build(); // @formatter:on } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //enabling swagger-ui part for visual documentation registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
6、验证Swagger2的JSON格式文档
启动项目,访问地址http://localhost:8080/swagger2-demo/v2/api-docs,会生成一个JSON格式的文档
7、验证Swagger2 UI文档
打开链接http://localhost:8080/swagger2-demo/swagger-ui.html#/swagger-2-demo-rest-controller 在浏览器中来查看Swagger UI文档
8、默认生成的API文档很好,但是它们缺乏详细的API级别信息。Swagger提供了一些注释,可以将这些详细信息添加到api中。如:@Api
–我们可以添加这个注解在controller上,去添加一个基本的controller说明,@ApiOperation and @ApiResponses
– 我们添加这个注解到任何controller的rest方法上来给方法添加基本的描述
新的Swagger2DemoRestController.java
package com.testswagger.controller; import com.testswagger.model.Student; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author xmh * @description swagger的controller * @Date 2020/1/7 */ @Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!") @RestController public class Swagger2DemoRestController { Liststudents = new ArrayList (); { students.add(new Student("Sajal", "IV", "India")); students.add(new Student("Lokesh", "V", "India")); students.add(new Student("Kajal", "III", "USA")); students.add(new Student("Sukesh", "VI", "USA")); } @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents") @ApiResponses(value = { @ApiResponse(code = 200, message = "Suceess|OK"), @ApiResponse(code = 401, message = "not authorized!"), @ApiResponse(code = 403, message = "forbidden!!!"), @ApiResponse(code = 404, message = "not found!!!") }) @RequestMapping(value = "/getStudents") public List getStudents() { return students; } @ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent") @RequestMapping(value = "/getStudent/{name}") public Student getStudent(@PathVariable(value = "name") String name) { return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); } @ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry") @RequestMapping(value = "/getStudentByCountry/{country}") public List getStudentByCountry(@PathVariable(value = "country") String country) { System.out.println("Searching Student in country : " + country); List studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)) .collect(Collectors.toList()); System.out.println(studentsByCountry); return studentsByCountry; } @RequestMapping(value = "/getStudentByClass/{cls}") public List getStudentByClass(@PathVariable(value = "cls") String cls) { return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList()); } }
新的Student.java
package com.testswagger.model; import io.swagger.annotations.ApiModelProperty; /** * @author xmh * @description Student实体类 * @Date 2020/1/7 */ public class Student { @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name") private String name; @ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class") private String cls; @ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country") private String country; public Student(String name, String cls, String country) { super(); this.name = name; this.cls = cls; this.country = country; } public String getName() { return name; } public String getCls() { return cls; } public String getCountry() { return country; } @Override public String toString() { return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]"; } }
9、打开http://localhost:8080/swagger2-demo/swagger-ui.html 在浏览器中查看Swagger ui 文档。