Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 视频教程 | 打赏(Donations) | About
知乎专栏多维度架构 微信号 netkiller-ebook | QQ群:128659835 请注明“读者”

5.36. Spring boot with Swagger2

5.36.1. Maven 文件

		
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.netkiller</groupId>
		<artifactId>parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<groupId>cn.netkiller</groupId>
	<artifactId>swagger2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>swagger2</name>
	<url>http://www.netkiller.cn</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<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>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

		
		

5.36.2. SpringApplication

		
package cn.netkiller.swagger2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		System.out.println("Swagger2!");
		SpringApplication.run(Application.class, args);
	}
}

		
		

5.36.3. EnableSwagger2

		
package cn.netkiller.swagger2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Predicate;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
import static com.google.common.base.Predicates.or;

@Configuration
@EnableSwagger2
public class Swagger2Configuration {
	@Bean
	public Docket postsApi() {
		return new Docket(DocumentationType.SWAGGER_2).groupName("public").apiInfo(apiInfo()).select().paths(postPaths()).build();
	}

	private Predicate<String> postPaths() {
		return or(regex("/api/.*"), regex("/public/api/.*"));
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("Open API").description("Open API reference for developers").termsOfServiceUrl("http://api.netkiller.cn").contact(new Contact("Neo Chen", "http://www.netkiller.cn", "netkiller@msn.com")).license("Mit License").licenseUrl("").version("1.0").build();
	}

}

		
		

5.36.4. RestController

		
package cn.netkiller.swagger2;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@RequestMapping(method = RequestMethod.GET, value = "/api/hello")
	public String sayHello() {
		return "Swagger Hello World";
	}
}
		
		

5.36.5. @Api()

用于类;表示标识这个类是swagger的资源tags,value 是说明,可以使用tags替代, tags如果有多个值,生成多个list

		
@Api(value="用户控制器",tags={"用户操作接口"})
@RestController
public class UserController {

}
		
		

5.36.6. @ApiOperation()

用于方法;表示一个http请求的操作,value用于方法描述,notes用于提示内容,tags可以重新分组

		
@ApiImplicitParams() 请求参数,包含多个 @ApiImplicitParam 
@ApiImplicitParam()  
name–参数ming 
value–参数说明 
dataType–数据类型 
paramType–参数类型 
example–举例说明		
		
		
		
package cn.netkiller.swagger2;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "test", tags = "test")
@RestController
@RequestMapping("/api/test")
public class TestController {
	@ApiOperation(value = "接口说明", notes = "接口说明")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "唯一ID", dataType = "Integer"), @ApiImplicitParam(name = "name", value = "名字") })
	@RequestMapping(value = "/name", method = { RequestMethod.GET, RequestMethod.POST })
	public String test(@RequestParam(value = "id", required = true) String id, @RequestParam(value = "name", required = true) String name) {
		return String.format("%s:%s", id, name);
	}
	
	@ApiOperation(value = "getGreeting", notes="get greeting",nickname = "getGreeting")
	@RequestMapping(method = RequestMethod.GET, value = "/api/javainuse")
	public <Hello> sayHello() {
		ArrayList<Hello> arrayList= new ArrayList<>();
			arrayList.add(new Hello());
		return arrayList;
	}

}
		
		

5.36.7. @ApiResponses

		
	@ApiOperation(value = "getGreeting", nickname = "getGreeting")
	@ApiResponses(value = {
		        @ApiResponse(code = 500, message = "Server error"),
		         @ApiResponse(code = 404, message = "Service not found"),
		        @ApiResponse(code = 200, message = "Successful retrieval",
		            response = Hello.class, responseContainer = "List") })
	@RequestMapping(method = RequestMethod.GET, value = "/api/javainuse")
	public <Hello> sayHello() {
			ArrayList<Hello> arrayList= new ArrayList<>();
			arrayList.add(new Hello());
		return arrayList;
	}
		
		

5.36.8. @ApiModel 实体类

		
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收 
value–表示对象名,description–描述,都可省略 

@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改 
value 字段说明 
name 重写属性名字 
dataType 重写属性类型 
required 是否必填 
example 举例说明 
hidden 隐藏		
		
		
		
package cn.netkiller.swagger2;

import java.io.Serializable;
import java.util.List;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "User", description = "通用用户对象")
public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	@ApiModelProperty(value = "用户名", name = "username", example = "neo")
	private String username = "Neo";
	private String password = "passw0rd";
	private String nickname = "netkiller";
	@ApiModelProperty(value = "状态", name = "state", example = "false", required = true)
	private boolean state = false;

	@ApiModelProperty(value = "字符串数组", hidden = true)
	private String[] array;
	private List<String> list;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public boolean isState() {
		return state;
	}

	public void setState(boolean state) {
		this.state = state;
	}

	public String[] getArray() {
		return array;
	}

	public void setArray(String[] array) {
		this.array = array;
	}

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

}
		
		
		
package cn.netkiller.swagger2;

import java.io.Serializable;
import java.util.List;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "测试", tags = "test")
@RestController
@RequestMapping("/api/test")
public class TestController {
	@ApiOperation("更改用户信息")
	@PostMapping("/user/info")
	public User userInfo(@RequestBody @ApiParam(name = "用户对象", value = "传入json格式", required = true) User user) {

		return user;
	}
}