Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

1.21. Spring boot with Swagger

1.21.1. Spring boot with Springdoc

https://springdoc.org

WebMvc

Ui

			
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
			
			

Api

			
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
      <version>2.3.0</version>
   </dependency>			
			
			

Webflux

			
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
      <version>2.3.0</version>
   </dependency>			
			
			

从 SpringFox 迁移到 Swagger3 注解变化

			
@Api → @Tag
@ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden
@ApiImplicitParam → @Parameter
@ApiImplicitParams → @Parameters
@ApiModel → @Schema
@ApiModelProperty(hidden = true) → @Schema(accessMode = READ_ONLY)
@ApiModelProperty → @Schema
@ApiOperation(value = "foo", notes = "bar") → @Operation(summary = "foo", description = "bar")
@ApiParam → @Parameter
@ApiResponse(code = 404, message = "foo") → @ApiResponse(responseCode = "404", description = "foo")			
			
			

1.21.2. Spring boot with knife4j

maven

		
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
            <version>4.4.0</version>
        </dependency>		
		
			

Knife4jConfiguration

		
package cn.netkiller.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Knife4jConfiguration {
    @Bean
    public GroupedOpenApi adminApi() {      // 创建了一个api接口的分组
        return GroupedOpenApi.builder()
                .group("default")         // 分组名称
                .pathsToMatch("/**")  // 接口请求路径规则
                .build();
    }

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("netkiller")
                        .description("接口描述")
                        .version("v1.0.0")
                        .contact(new Contact().name("neo").email("netkiller@msn.com"))
                        .license(new License().name("Apache 2.0").url("https://www.netkiller.cn/docs"))
                ).externalDocs(new ExternalDocumentation()
                        .description("外部文档")
                        .url("https://www.netkiller.cn/docs"));

    }

}		
		
			

application.properties

		
# springdoc-openapi项目配置
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.tags-sorter=alpha
springdoc.swagger-ui.operations-sorter=alpha
springdoc.api-docs.path=/v3/api-docs
# knife4j的增强配置,不需要增强可以不配
knife4j.enable=true
knife4j.setting.language=zh_cn		
		
			

1.21.3. springfox

Swagger3

		
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
		
			

1.21.3.1. Swagger2

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>

		
				
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);
	}
}

		
				
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();
	}

}

		
				
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";
	}
}
		
				

1.21.3.2. @Api() 资源定义

标签分类

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

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

}
		
			

@ApiIgnore 忽律接口

		
		
		
		

@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;
	}

}
		
		

@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;
	}
		
		

@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;
	}
}