【重要提示】:目前已有更好的方法,可以参考:Swagger2 导出离线 word文档
项目源码下载:spring-boot-swagger2.zip
/swagger2-demo
context 路径启动应用.
server.contextPath=/swagger2-demo
3.添加一个REST的contrller,名称为Swagger2DemoRestController,他将会
为学生实体提供基本的基于REST的功能。package com.example.springbootswagger2.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springbootswagger2.model.Student;
@RestController
public class Swagger2DemoRestController {
List<Student> students = new ArrayList<Student>();
{
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<Student> 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<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
System.out.println("Searching Student in country : " + country);
List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
.collect(Collectors.toList());
System.out.println(studentsByCountry);
return studentsByCountry;
}
@RequestMapping(value = "/getStudentByClass/{cls}")
public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
}
}
package com.example.springbootswagger2.model;
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.以spring boot方式启动这个程序应用。测试下面的一两个REST端点来检查他们是否正常工作:
springfox-swagger2
、springfox-swagger-ui
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
package com.example.springbootswagger2.configuration;
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 com.google.common.base.Predicates;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@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/");
}
}
@Api
–我们可以添加这个注解在controller上,去添加一个基本的controller说明
@Api(value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!")
@RestController
public class Swagger2DemoRestController {
//...
}
@ApiOperation and @ApiResponses
– 我们添加这个注解到任何controller的rest方法上来给方法添加基本的描述。例如:
@ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/getStudents")
public List<Student> getStudents() {
return students;
}
在这里,我们可以向方法中添加标签,来在swagger-ui
中添加一些分组。@ApiModelProperty
– 这个注解用来在数据模型对象中的属性上添加一些描述,会在Swagger UI中展示模型的属性。例如:
@ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
private String name;
Controller 和 Model 类添加了swagger2注解之后,代码清单:package com.example.springbootswagger2.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springbootswagger2.model.Student;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!")
@RestController
public class Swagger2DemoRestController {
List<Student> students = new ArrayList<Student>();
{
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<Student> 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<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
System.out.println("Searching Student in country : " + country);
List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
.collect(Collectors.toList());
System.out.println(studentsByCountry);
return studentsByCountry;
}
// @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass")
@RequestMapping(value = "/getStudentByClass/{cls}")
public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
}
}
Student.java
package com.example.springbootswagger2.model;
import io.swagger.annotations.ApiModelProperty;
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 + "]";
}
}
https://www.leftso.com/article/223.html