betway必威-betway必威官方网站
做最好的网站

SpringBoot学习笔记之集成swagger,Swagger2在SpringBoo

Swagger2在SpringBoot境遇下的运用

合龙步骤

第四章 springboot swagger,springbootswagger

注:本文参照他事他说加以侦查自

 

swagger用于定义API文档。

好处:

  • 上下端抽离开荒
  • API文书档案非常分明
  • 测量检验的时候没有供给再利用U奥迪Q7L输入浏览器的不二秘技来访谈Controller
  • 历史观的输入USportageL的测量试验方法对于post诉求的传参相比较麻烦(当然,能够应用postman那样的浏览器插件)
  • spring-boot与swagger的购并轻松的风流倜傥逼

1、项目社团

和上生龙活虎节相符,没有纠正。

2、pom.xml

引进了多少个jar。

图片 1 1 <dependency> 2 <groupId>io.springfox</groupId> 3 <artifactId>springfox-swagger2</artifactId> 4 <version>2.2.2</version> 5 </dependency> 6 <dependency> 7 <groupId>io.springfox</groupId> 8 <artifactId>springfox-swagger-ui</artifactId> 9 <version>2.2.2</version> 10 </dependency> View Code

3、Application.java

图片 2 1 package com.xxx.firstboot; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 import springfox.documentation.swagger2.annotations.EnableSwagger2; 7 8 @SpringBootApplication //same as @[email protected][email protected] 9 @EnableSwagger2 //启动swagger注解 10 public class Application { 11 12 public static void main(String[] args) { 13 SpringApplication.run(Application.class, args); 14 } 15 16 } View Code

说明:

  • 引进了多个疏解@EnableSwagger2来运营swagger申明。(运营该注解使得用在controller中的swagger表明生效,覆盖的约束由@ComponentScan的铺排来钦定,这里私下认可内定为根路线"com.xxx.firstboot"下的有所controller)

4、UserController.java

图片 3 1 package com.xxx.firstboot.web; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.RequestHeader; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestMethod; 7 import org.springframework.web.bind.annotation.RequestParam; 8 import org.springframework.web.bind.annotation.RestController; 9 10 import com.xxx.firstboot.domain.User; 11 import com.xxx.firstboot.service.UserService; 12 13 import io.swagger.annotations.Api; 14 import io.swagger.annotations.ApiImplicitParam; 15 import io.swagger.annotations.ApiImplicitParams; 16 import io.swagger.annotations.ApiOperation; 17 import io.swagger.annotations.ApiResponse; 18 import io.swagger.annotations.ApiResponses; 19 20 @RestController 21 @RequestMapping("/user"卡塔尔 22 @Api("userController相关api"卡塔尔(قطر‎ 23 public class UserController { 24 25 @Autowired 26 private UserServiceuserService; 27 28 // @Autowired 29 // private MyRedisTemplate myRedisTemplate; 30 31 @ApiOperation("获取客商音讯"卡塔尔 32 @ApiImplicitParams({ 33 @ApiImplicitParam(paramType="header",name="username",dataType="String",required=true,value="客户的人名",defaultValue="zhaojigang"卡塔尔(英语:State of Qatar), 34 @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="客户的密码",defaultValue="wangna"卡塔尔国35 }卡塔尔(قطر‎ 36 @ApiResponses({ 37 @ApiResponse(code=400,message="恳求参数没填好"卡塔尔(قطر‎, 38 @ApiResponse(code=404,message="央求路线未有或页面跳转路线不对"卡塔尔(قطر‎ 39 }卡塔尔国 40 @RequestMapping(value="/getUser",method=RequestMethod.GET卡塔尔(英语:State of Qatar) 41 public User getUser(@RequestHeader("username"卡塔尔(英语:State of Qatar) String username, @RequestParam("password"卡塔尔(英语:State of Qatar) String password卡塔尔(قطر‎ { 42 return userService.getUser(username,password卡塔尔(قطر‎; 43 } 44 45 // @RequestMapping("/testJedisCluster"卡塔尔(قطر‎ 46 // public User testJedisCluster(@RequestParam("username"卡塔尔(قطر‎ String username卡塔尔{ 47 // String value = myRedisTemplate.get(MyConstants.USESportage_FORWARD_CACHE_PREFIX, username); 48 // if(StringUtils.isBlank(value)){ 49 // myRedisTemplate.set(MyConstants.USER_FORWARD_CACHE_PREFIX, username, JSON.toJSONString(getUser())); 50 // return null; 51 // } 52 // return JSON.parseObject(value, User.class); 53 // } 54 55 } View Code

说明:

  • @Api:用在类上,表达该类的效率
  • @ApiOperation:用在章程上,表明方法的效果
  • @ApiImplicitParams:用在方式上含蓄大器晚成组参数表明
  • @ApiImplicitParam:用在@ApiImplicitParams声明中,内定五个呼吁参数的各样方面
    • paramType:参数放在哪个地点
      • header-->央求参数的拿到:@RequestHeader
      • query-->诉求参数的收获:@RequestParam
      • path(用于restful接口)-->恳求参数的得到:@PathVariable
      • body(不常用)
      • form(不常用)
    • name:参数名
    • dataType:参数类型
    • required:参数是还是不是必得传
    • value:参数的野趣
    • defaultValue:参数的暗中同意值
  • @ApiResponses:用于表示风华正茂组响应
  • @ApiResponse:用在@ApiResponses中,日常用来表明一个荒谬的响应音信
    • code:数字,例如400
    • message:新闻,比如"诉求参数没填好"
    • response:抛出十二分的类

以上这几个即是最常用的几个申明了。

现实其余的讲解,查看:

 

测试:

运营服务,浏览器输入""

图片 4

最顶部一个红框:@Api

GET红框:method=RequestMethod.GET

左边红框:@ApiOperation

parameter红框:@ApiImplicitParams类别表明

response messages红框:@ApiResponses种类注明

输入参数后,点击"try it out!",查看响应内容:

图片 5

 

springboot swagger,springbootswagger 注:本文参照他事他说加以考查自 swagger用于定义API文书档案。 好处: 前后端抽离开拓 API文书档案...

1. 集成Swagger

1、在pom.xml中援引度swagger依赖包

1.1 增添信任

<!--swagger2 start-->

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.6.1</version>

</dependency>

<!--引入swagger-ui包-->

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.6.1</version>

</dependency>

 

<dependency>

1.2 配置类

package com.inn.demo.config;

 

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

 

@Configuration

@EnableSwagger2

public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

//生产关闭swagger

@Value("${swagger.enable}")

private boolean enableSwagger;

 

// /**

// * 访谈swagger ui 现身404时能够把注释去掉试试

// * 消除能源系统财富目录与swagger ui能源目录冲突难题

// * 那几个地点要双重注入一下财富文件,不然不会注入能源的,也未尝流入requestHandlerMappping,也正是xml配置的swagger能源配置

// * <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>

// * <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>

// * @param registry

// */

// @Override

// public void addResourceHandlers(ResourceHandlerRegistry registry) {

// registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");

// registry.addResourceHandler("swagger-ui.html")

// .addResourceLocations("classpath:/META-INF/resources/");

// registry.addResourceHandler("/webjars/**")

// .addResourceLocations("classpath:/META-INF/resources/webjars/");

// super.addResourceHandlers(registry);

// }

 

// /**

// * 扶植分组 groupName

// */

// @Bean(value = "solrRestApi")

// public Docket createSolrRestApi() {

// return new Docket(DocumentationType.SWAGGER_2)

// .apiInfo(apiInfo()).groupName("Solr Demo模块")

// .enable(enableSwagger)

// .select()

// .apis(RequestHandlerSelectors.basePackage("com.inn.demo.modules.solr.web"))

// .paths(PathSelectors.any())

// .build();

// }

 

@Bean(value = "userRestApi")

public Docket createUserRestApi() {

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

//.groupName("客户管理"卡塔尔(قطر‎

.enable(enableSwagger)

.globalOperationParameters(createCommonParams(卡塔尔国卡塔尔(英语:State of Qatar)//公共参数

.select()

.apis(RequestHandlerSelectors.basePackage("com.inn.demo.modules.user.web"))

.paths(PathSelectors.any())

.build();

}

 

private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.title("Demo APIs")

.description("应用实例"卡塔尔(英语:State of Qatar)

//.termsOfServiceUrl(";)

//.contact(new Contact("开发者1", "", "xxx@163.com"))

.version("1.0")

.build();

}

/**
 * 创建公共参数
 * @return
 */
private List<Parameter> createCommonParams() {
    //添加head参数start
    List<Parameter> pars = new ArrayList<Parameter>();

    ParameterBuilder tokenPar = new ParameterBuilder();
    tokenPar.name("x-access-token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();

    pars.add(tokenPar.build());

    return pars;
    //添加head参数end
}

}

 

<groupId>io.springfox</groupId>

1.3 表明使用

功用范围

API

行使位置

对象属性

@ApiModelProperty

用在进出参数对象的字段上

合计集陈述

@Api

用于controller类上

共谋描述

@ApiOperation

用在controller的格局上

Response集

@ApiResponses

用在controller的法子上

Response

@ApiResponse

用在 @ApiResponses里边

非对象参数集

@ApiImplicitParams

用在controller的章程上

非对象参数描述

@ApiImplicitParam

用在@ApiImplicitParams的格局里边

陈诉重临对象的意思

@ApiModel

用在回去对象类上

ApiImplicitParam的连锁属性

属性

取值

作用

paramType

path

query

body

header

form

参数放在哪个地方:一定要有其生龙活虎脾性

header:header中提交:@RequestHeader获取

query :key=value提交:@RequestParam获取

path  :地址中提交:@PathVariable获取

body  :json流提交 :@RequestBody获取(限POST)

form  :表单提交:@RequestParam获取(限POST)

dataType

Long

String

参数的数据类型 只作为标识表明,并从未实际验证

name

 

摄取参数名

value

 

收起参数的意思描述

required

 

参数是否必填

 

TRUE

必填

 

FALSE

非必填

defaultValue

 

默认值

ApiImplicitParam 与 ApiParam 的区别

ApiImplicitParam: 

  • 对Servlets大概非 JAX-智跑S的情状,只好接纳 ApiImplicitParam。
  • 在利用上,ApiImplicitParam比ApiParam具备越来越少的代码侵入性,只要写在章程上就足以了,不过必要提供切实的性格本事协作swagger ui分析使用。
  • ApiParam只需求相当少的性子,与swagger ui合营更加好。

 

代码实例:

@RestController

@RequestMapping(value = "/user")

@Api(value = "/user", description = "职员基本新闻 "卡塔尔

public class UserController {

 

static Map<String, User> users = Collections.synchronizedMap(new HashMap<String, User>());

 

@ApiOperation(value = "获取用户列表", notes = ""卡塔尔国

@RequestMapping(value = {"/list"}, method = RequestMethod.GET)

public List<User> getUserList() {

List<User> r = new ArrayList<User>(users.values());

return r;

}

 

@ApiOperation(value = "创立客户", notes = "根据User对象成立客商"卡塔尔

@ApiImplicitParam(name = "user", value = "客户详细实体user", required = true, dataType = "User"卡塔尔

@RequestMapping(value = "add", method = RequestMethod.POST)

public String postUser(@RequestBody User user) {

users.put(user.getId(), user);

return "success";

}

 

@ApiOperation(value = "获取客商详细音信", notes = "依照url的id来博取客商详细消息"卡塔尔

@ApiParam(name = "id", value = "用户ID", required = true)

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)

public User getUser(@PathVariable(value = "id") String id) {

return users.get(id);

}

 

@ApiOperation(value = "更新客户详细音信", notes = "依照url的id来内定更新目的,并依据传过来的user新闻来更新顾客详细消息"卡塔尔(قطر‎

@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)

public String putUser(@PathVariable @ApiParam(name = "id", value = "用户ID", required = true) String id,

@RequestBody @ApiParam(name = "user", value = "顾客详细实体user", required = true卡塔尔(قطر‎ User user卡塔尔(قطر‎{

User u = users.get(id);

u.setName(user.getName());

u.setAge(user.getAge());

users.put(id, u);

return "success";

}

 

@ApiOperation(value = "更新顾客名称和年龄", notes = "更新客商名称和年龄"卡塔尔(英语:State of Qatar)

@ApiImplicitParams({

@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String",paramType = "path"),

@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String",paramType = "query"),

@ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "Integer",paramType = "query"),

@ApiImplicitParam(name = "user", value = "客商音信", required = true, dataType = "User",paramType = "body"卡塔尔(قطر‎,

@ApiImplicitParam(name = "headerName", value = "Header信息", required = true, dataType = "String",paramType = "header")

})

@RequestMapping(value = "/update/info/{id}", method = RequestMethod.POST)

public String updateUserNameAndAge(@PathVariable(value = "id") String id,

@RequestParam(value = "name") String name,

@RequestParam(value = "age") Integer age,

@RequestHeader(value = "headerName") String headerName,

@RequestBody User user) {

User u = users.get(id);

u.setName(name);

u.setAge(age);

users.put(id, u);

return "success";

}

 

@ApiOperation(value = "删除客户", notes = "根据url的id来钦命删除对象")

@ApiParam(name = "id", value = "用户ID", required = true)

@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)

public String deleteUser(@PathVariable String id) {

users.remove(id);

return "success";

}

 

@ApiOperation(value="删除顾客-传递数组", notes="删除对象,传递数组"卡塔尔国

@RequestMapping(value="/users/deleteByIds", method = RequestMethod.DELETE)

public void deleteUsers(@ApiParam("用户ID数组") @RequestParam Integer[] ids) {

for (int id:ids){

users.remove(id);

}

}

}

User实体类:

 

@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})

@ApiModel(value = "User")

public class User {

@ApiModelProperty(value = "ID")

private String id;

 

@ApiModelProperty(value = "姓名", required = true)

private String name;

 

@ApiModelProperty(value = "年龄")

private Integer age;

 

public String getId() {

return id;

}

 

public void setId(String id) {

this.id = id;

}

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public Integer getAge() {

return age;

}

 

public void setAge(Integer age) {

this.age = age;

}

}

 

<artifactId>springfox-swagger2</artifactId>

1.4 访谈调控台

 

按以下步骤配置,项目运行后拜候:

<version>2.6.1</version>

1.5 可选配置

在application.properties中步向以下配置,用于安装测量试验央浼的host,暗中认可在swagger ui上做诉求测量试验时都以以/users/1为路线发送央求。

只要须要更换哀告的根路线,就须要配备那个参数:

该Host也是swagger-ui发送测验诉求的Host, 日常大家会将将接口文书档案布署在测验服务器,那样就必要设置Host,

不然央求都以透过localhost发送,哀告不到测量检验服务器的接口。

springfox.documentation.swagger.v2.host = yourapp.abc.com

布置获取api docs json数据的倡议路线 ,默感觉/v2/api-docs:

springfox.documentation.swagger.v2.path = /api

 

</dependency>

2. 变动静态API文书档案pdf

<dependency>

2.1 Maven 配置

======属性配置=======

<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>

<asciidoctor.input.directory>${project.basedir}/docs/asciidoc</asciidoctor.input.directory>

<generated.asciidoc.directory>${project.build.directory}/asciidoc</generated.asciidoc.directory>

<asciidoctor.html.output.directory>${project.build.directory}/asciidoc/html</asciidoctor.html.output.directory>

<asciidoctor.pdf.output.directory>${project.build.directory}/asciidoc/pdf</asciidoctor.pdf.output.directory>

 

=====信赖配置============

<!--离线文书档案-->

<dependency>

<groupId>org.springframework.restdocs</groupId>

<artifactId>spring-restdocs-mockmvc</artifactId>

<version>1.1.2.RELEASE</version>

<scope>test</scope>

</dependency>

<!--springfox-staticdocs 生成静态文书档案-->

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-staticdocs</artifactId>

<version>2.6.1</version>

</dependency>

<!--swagger2 end-->

 

============插件配置==========

<!--通过Asciidoctor使得asciidoc生成别的的文书档案格式,举例:PDF 或许HTML5-->

<plugin>

<groupId>org.asciidoctor</groupId>

<artifactId>asciidoctor-maven-plugin</artifactId>

<version>1.5.3</version>

<!--生成PDF-->

<dependencies>

<dependency>

<groupId>org.asciidoctor</groupId>

<artifactId>asciidoctorj-pdf</artifactId>

<version>1.5.0-alpha.14</version>

</dependency>

<!-- Comment this section to use the default jruby artifact provided by the plugin -->

<dependency>

<groupId>org.jruby</groupId>

<artifactId>jruby-complete</artifactId>

<version>1.7.21</version>

</dependency>

</dependencies>

 

<!--文档生成配置-->

<configuration>

<sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>

<sourceDocumentName>index.adoc</sourceDocumentName>

<attributes>

<doctype>book</doctype>

<toc>left</toc>

<toclevels>3</toclevels>

<numbered></numbered>

<hardbreaks></hardbreaks>

<sectlinks></sectlinks>

<sectanchors></sectanchors>

<generated>${generated.asciidoc.directory}</generated>

</attributes>

</configuration>

<!--因为老是执行只可以管理四个后端,所以对于各类想要的出口类型,都是单独分开施行-->

<executions>

<!--html5-->

<execution>

<id>output-html</id>

<phase>test</phase>

<goals>

<goal>process-asciidoc</goal>

</goals>

<configuration>

<backend>html5</backend>

<outputDirectory>${asciidoctor.html.output.directory}</outputDirectory>

</configuration>

</execution>

<!--pdf-->

<execution>

<id>output-pdf</id>

<phase>test</phase>

<goals>

<goal>process-asciidoc</goal>

</goals>

<configuration>

<backend>pdf</backend>

<outputDirectory>${asciidoctor.pdf.output.directory}</outputDirectory>

</configuration>

</execution>

</executions>

</plugin>

 

 

<groupId>io.springfox</groupId>

2.2 创建index.adoc文件

路径:项目名/docs/asciidoc/index.adoc

内容:

  1. include::{generated}/overview.adoc[]  
  2. include::{generated}/definitions.adoc[]  
  3. include::{generated}/paths.adoc[]  

 

<artifactId>springfox-swagger-ui</artifactId>

2.3 创造生成pdf、html的测验类

package com.inn.demo;

 

import io.github.robwin.markup.builder.MarkupLanguage;

import io.github.robwin.swagger2markup.GroupBy;

import io.github.robwin.swagger2markup.Swagger2MarkupConverter;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;

import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.http.MediaType;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;

import springfox.documentation.staticdocs.SwaggerResultHandler;

 

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

 

@AutoConfigureMockMvc

@AutoConfigureRestDocs(outputDir = "target/generated-snippets")

@RunWith(SpringRunner.class)

@SpringBootTest

public class Swagger2MarkupTest {

private String snippetDir = "target/generated-snippets";

private String outputDir = "target/asciidoc";

 

@Autowired

private WebApplicationContext context;

 

private MockMvc mockMvc;

 

@Before

public void setUp() {

this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();

}

 

/**

* 生成api html、pdf

* @throws Exception

*/

@Test

public void Test() throws Exception {

// 得到swagger.json,写入outputDir目录中

mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON))

.andDo(SwaggerResultHandler.outputDirectory(outputDir).build())

.andExpect(status().isOk())

.andReturn();

// 读取上一步生成的swagger.json转成asciiDoc,写入到outputDir

// 那几个outputDir必需和插件里面<generated></generated>标签配置风华正茂致

Swagger2MarkupConverter.from(outputDir   "/swagger.json")

.withPathsGroupedBy(GroupBy.TAGS)// 按tag排序

.withMarkupLanguage(MarkupLanguage.ASCIIDOC)// 格式

.withExamples(snippetDir)

.build()

.intoFolder(outputDir);// 输出

}

}

 

运维测量检验类就可以生成pdf、html

  1. 生成的PDF和HTML文件:target/asciidoc/html and target/asciidoc/pdf  

  2. Swagger-UI 汉化


<version>2.6.1</version>

3.1 增多自定义首页和译文

在resourece目录下开创META-INFresourece目录,然后创立三个名号为"swagger-ui.html" 的HTML文件

图片 6

html内容:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Swagger UI</title>

<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>

<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>

<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>

<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>

<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>

<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>

<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>

<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script> <!--国际化操作:选用汉语版 -->

<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>

</head>

<body class="swagger-section">

<div id='header'>

<div class="swagger-ui-wrap">

<a id="logo" href="javascript:void(0)">

<img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" />

<span class="logo__title">在线API</span>

</a>

<form id='api_selector'>

<div class='input'>

<select id="select_baseUrl" name="select_baseUrl"></select>

</div>

<div class='input'>

<input placeholder="; id="input_baseUrl" name="baseUrl" type="text"/>

</div>

<div id='auth_container'></div>

<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>

</form>

</div>

</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate></div>

<div id="swagger-ui-container" class="swagger-ui-wrap"></div>

</body>

</html>

马到成功大家寻访 http://localhost:8080/swagger-ui.html 看看显示效果:

图片 7

</dependency>

3.2 更详实的汉化

假定想进一层调动译文,能够在META-INFresourceswebjarsspringfox-swagger-uilang 目录下增添zh-cn.js文件.

图片 8

 

下一场在译文(zh-cn.js )内容,如下

'use strict';

 

/* jshint quotmark: double */

window.SwaggerTranslator.learn({

"Warning: Deprecated":"警告:已过时",

"Implementation Notes":"完成备注",

"Response Class":"响应类",

"Status":"状态",

"Parameters":"参数",

"Parameter":"参数",

"Value":"值",

"Description":"描述",

"Parameter Type":"参数类型",

"Data Type":"数据类型",

"Response Messages":"响应新闻",

"HTTP Status Code":"HTTP状态码",

"Reason":"原因",

"Response Model":"响应模型",

"Request URL":"请求URL",

"Response Body":"响应体",

"Response Code":"响应码",

"Response Headers":"响应头",

"Hide Response":"隐蔽响应",

"Headers":"头",

"Try it out!":"试一下!",

"Show/Hide":"显示/隐藏",

"List Operations":"展现操作",

"Expand Operations":"张开操作",

"Raw":"原始",

"can't parse JSON. Raw result":"不恐怕深入分析JSON. 原始结果",

"Example Value":"示例",

"Click to set as parameter value":"点击设置参数",

"Model Schema":"模型布局",

"Model":"模型",

"apply":"应用",

"Username":"用户名",

"Password":"密码",

"Terms of service":"服务条约",

"Created by":"创建者",

"See more at":"查看愈来愈多:",

"Contact the developer":"联系开荒者",

"api version":"api版本",

"Response Content Type":"响应Content Type",

"Parameter content type:":"参数类型:",

"fetching resource":"正在收获财富",

"fetching resource list":"正在拿到能源列表",

"Explore":"浏览",

"Show Swagger Petstore Example Apis":"显示 Swagger Petstore 示例 Apis",

"Can't read from server. It may not have the appropriate access-control-origin settings.":"不可能从服务器读取。大概未有精确设置access-control-origin。",

"Please specify the protocol for":"请钦命左券:",

"Can't read swagger JSON from":"不能够读取swagger JSON于",

"Finished Loading Resource Information. Rendering Swagger UI":"已加载能源消息。正在渲染Swagger UI",

"Unable to read api":"无法读取api",

"from path":"从路径",

"server returned":"服务器再次回到"

});

居功至伟告成!

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-core</artifactId>

<version>2.6.5</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.6.5</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-annotations</artifactId>

<version>2.6.5</version>

</dependency>

2、创建swager配置类

package com.vk.liyj.config;

import io.swagger.annotations.ApiOperation;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**

* 类描述:配置swagger2信息

*/

@Configuration // 让Spring来加载该类配置

//@EnableWebMvc // 启用Mvc,非springboot框架必要引进注脚@EnableWebMvc

@EnableSwagger2 // 启用Swagger2

public class Swagger2Config {

@Bean

public Docket createRestApi() {

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

.select()

// 扫描钦命包中的swagger注脚

// .apis(RequestHandlerSelectors.basePackage("com.vk.liyj"))

// 扫描全部有评释的api,用这种方法更加灵敏

.apis(RequestHandlerSelectors

.withMethodAnnotation(ApiOperation.class))

.paths(PathSelectors.any()).build();

}

private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.title("底子平台 RESTful APIs"卡塔尔(قطر‎

.description(

"底子平台 RESTful 风格的接口文书档案,内容详细,很大的收缩了上下端的交换花销,同时确定保障代码与文书档案保持中度风华正茂致,不小的压缩维护文书档案的时刻。"卡塔尔国

.termsOfServiceUrl("")

.contact("Xia").version("1.0.0").build();

}

}

因此@Configuration申明,申明它是二个安插类,@EnableSwagger2开启swagger2。apiINfo(卡塔尔国配置部分大旨的音信。apis(卡塔尔(英语:State of Qatar)钦定扫描的包会生成文书档案。

3、编写swagger注解

package com.vk.liyj.model;

import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import com.fasterxml.jackson.annotation.JsonInclude;

/**

* 人员音讯表 注明:@ApiModel 和 @ApiModelProperty 用于在通过对象吸取参数时在API文书档案中显示字段的表明

* 注脚:@DateTimeFormat 和 @JsonFormat 用于在接受和再次来到日期格式时将其格式化 实体类对应的数据表为: user_info

*

本文由betway必威发布于编程开发,转载请注明出处:SpringBoot学习笔记之集成swagger,Swagger2在SpringBoo

TAG标签: betway必威
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。