SpringBoot学习笔记之集成swagger

ui资源目录冲突问题,解决资源系统资源目录与swagger,非springboot框架需要引入注解@EnableWebMvc,扫描指定包中的swagger注解,引入了两个jar,– 使用数据源 –&gt,所以想要使用mybatis就要自己去集成

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>

 

@ApiOperation(value =
“依据用户id删除用户音信”, notes = “依据用户id删除用户新闻”)

第四章 springboot + swagger,springbootswagger

注:本文参考自

 

swagger用于定义API文书档案。

好处:

  • 前后端分离开发
  • API文书档案分外醒目
  • 测试的时候不须要再采纳U路虎极光L输入浏览器的章程来拜会Controller
  • 观念的输入ULacrosseL的测试方法对于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 壹 package
com.xxx.firstboot.web; 二 三 import
org.springframework.beans.factory.annotation.Autowired; 四 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; 八 import
org.springframework.web.bind.annotation.RestController; 九 十 import
com.xxx.firstboot.domain.User; 11 import
com.xxx.firstboot.service.UserService; 1二 壹叁 import
io.swagger.annotations.Api; 14 import
io.swagger.annotations.ApiImplicitParam; 一伍 import
io.swagger.annotations.ApiImplicitParams; 16 import
io.swagger.annotations.ApiOperation; 一七 import
io.swagger.annotations.ApiResponse; 18 import
io.swagger.annotations.ApiResponses; 1玖 20 @RestController 二一@RequestMapping(“/user”) 2二 @Api(“userController相关api”) 二3 public
class UserController { 2肆 二伍 @Autowired 26 private UserServiceuser瑟维斯; 27 28 // @Autowired 29 // private MyRedisTemplate
myRedisTemplate; 30 3一 @ApiOperation(“获取用户新闻”) 32@ApiImplicitParams({ 3三@ApiImplicitParam(paramType=”header”,name=”username”,dataType=”String”,required=true,value=”用户的全名”,defaultValue=”zhaojigang”),
34@ApiImplicitParam(paramType=”query”,name=”password”,dataType=”String”,required=true,value=”用户的密码”,defaultValue=”wangna”)
3五 }) 36 @ApiResponses({ 37@ApiResponse(code=400,message=”请求参数没填好”), 38@ApiResponse(code=40四,message=”请求路径未有或页面跳转路径不对”) 3九 }) 40
@RequestMapping(value=”/getUser”,method=RequestMethod.GET) 4一 public
User getUser(@RequestHeader(“username”) String username,
@RequestParam(“password”) String password) { 4二 return
userService.getUser(username,password); 四叁 } 4四 45 //
@RequestMapping(“/testJedisCluster”) 四陆 // public User
testJedisCluster(@RequestParam(“username”) String username){ 四七 //
String value =
myRedisTemplate.get(MyConstants.USEPRADO_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:用在情势上带有1组参数表达
  • @ApiImplicitParam:用在@ApiImplicitParams申明中,内定二个伸手参数的种种方面
    • paramType:参数放在哪个地点
      • header–>请求参数的收获:@RequestHeader
      • query–>请求参数的取得:@RequestParam
      • path(用于restful接口)–>请求参数的获取:@PathVariable
      • body(不常用)
      • form(不常用)
    • name:参数名
    • dataType:参数类型
    • required:参数是还是不是必须传
    • value:参数的意趣
    • defaultValue:参数的暗中同意值
  • @ApiResponses:用于表示1组响应
  • @ApiResponse:用在@ApiResponses中,1般用于表明二个荒谬的响应音讯
    • 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文书档案…

第五章 springboot + mybatis,springbootmybatis

springboot集成了springJDBC与JPA,不过从未集成mybatis,所以想要使用mybatis就要团结去集成。集成情势10分简单。

1、项目布局

图片 6

 

2、pom.xml

图片 7 1 <!–
与数据库操作相关的依赖 –> 二 <dependency> 3<groupId>org.springframework.boot</groupId> 4<artifactId>spring-boot-starter-jdbc</artifactId> 五</dependency> 陆 七 <!– 使用数据源 –> 捌 <dependency> 九<groupId>com.alibaba</groupId> 10<artifactId>druid</artifactId> 11<version>壹.0.14</version> 12 </dependency> 1叁 1肆<!– mysql –> 15 <dependency> 16
<groupId>mysql</groupId> 17
<artifactId>mysql-connector-java</artifactId> 18
<scope>runtime</scope> 19 </dependency> 20 21 <!–
mybatis –> 22 <dependency> 23
<groupId>org.mybatis</groupId> 24
<artifactId>mybatis</artifactId> 25
<version>3.2.8</version> 26 </dependency> 27
<dependency> 28 <groupId>org.mybatis</groupId> 29
<artifactId>mybatis-spring</artifactId> 30
<version>1.2.2</version> 31 </dependency> View Code

说明:

  • spring-boot-starter-jdbc:引入与数据库操作相关的依靠,例如daoSupport等

  • druid:Alibaba的数据源

  • mysql-connector-java:mysql连接jar,scope为runtime
  • mybatis + mybatis-spring:mybatis相关jar

 

3、application.properties

图片 81
jdbc.driverClassName = com.mysql.jdbc.Driver 2 jdbc.url =
jdbc:mysql://xxx:3306/mytestdb?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8
3 jdbc.username = root 4 jdbc.password = vvvxxx 5 6
mybatis.typeAliasesPackage=com.xxx.firstboot.domain 7
mybatis.mapperLocations=classpath:mapper/*.xml View Code

说明:

  • mybatis.typeAliasesPackage:钦命domain类的基包,即钦命其在*Mapper.xml文件中能够动用简名来替代全类名(看前边的UserMapper.xml介绍)
  • mybatis.mapperLocations:指定*Mapper.xml的位置

 

4、com.xxx.firstboot.common.MyBatisConfig

功能:mybatis与springboot集成的进口

图片 9 1 package
com.xxx.firstboot.common; 2 3 import java.util.Properties; 4 5 import
javax.sql.DataSource; 6 7 import
org.apache.ibatis.session.SqlSessionFactory; 8 import
org.mybatis.spring.SqlSessionFactoryBean; 9 import
org.mybatis.spring.annotation.MapperScan; 10 import
org.springframework.beans.factory.annotation.Autowired; 11 import
org.springframework.context.annotation.Bean; 12 import
org.springframework.context.annotation.Configuration; 13 import
org.springframework.core.env.Environment; 14 import
org.springframework.core.io.support.PathMatchingResourcePatternResolver;
15 16 import com.alibaba.druid.pool.DruidDataSourceFactory; 17 18 /**
19 * springboot集成mybatis的主干入口 20 * 一)创立数量源 二一 *
2)创建SqlSessionFactory 22 */ 二三 @Configuration
//该注脚类似于spring配置文件 二四@MapperScan(basePackages=”com.xxx.firstboot.mapper”) 二伍 public class
MyBatisConfig { 贰陆 二柒 @Autowired 2八 private Environment env; 2九 30 /**
31 * 创制数量源 3贰 * @Primary
该注化痰示在同三个接口有多个落到实处类能够注入的时候,暗中同意选项哪1个,而不是让@autowire声明报错
33 */ 34 @Bean 35 //@Primary 36 public DataSource getDataSource()
throws Exception{ 37 Properties props = new Properties(); 38
props.put(“driverClassName”, env.getProperty(“jdbc.driverClassName”));
39 props.put(“url”, env.getProperty(“jdbc.url”)); 40
props.put(“username”, env.getProperty(“jdbc.username”)); 41
props.put(“password”, env.getProperty(“jdbc.password”)); 42 return
DruidDataSourceFactory.createDataSource(props); 43 } 44 45 /** 46 *
根据数据源创立SqlSessionFactory 肆柒 */ 4八 @Bean 4玖 public
SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{ 50
SqlSessionFactoryBean fb = new SqlSessionFactoryBean(); 5一fb.setDataSource(ds);//钦点数据源(那一个必须有,不然报错) 52
//下面两句仅仅用于*.xml文件,若是整个持久层操作不供给利用到xml文件的话(只用注明就能够化解),则不加
伍三fb.setType阿里asesPackage(env.getProperty(“mybatis.typeAliasesPackage”));//钦命基包
5四 fb.setMapperLocations(new
PathMatchingResourcePatternResolver().getResources(env.getProperty(“mybatis.mapperLocations”)));//钦赐xml文件地点5伍 56 return fb.getObject(); 5柒 } 58 59 } View Code

说明:

  • 类上面添加八个
    • @Configuration注脚(该表明类似于spring的安顿文件)
    • @MapperScan表明,钦赐扫描的mapper接口所在的包
  • 在此类中,注入了Environment实例,使用该实例能够去读取类路径下application.properties文件中的内容,读取文件内容的二种艺术,见第1章
    第三个spring-boot程序
  • 在此类中,使用druid数据源定义了多少源Bean,spring-boot暗许使用的是tomcat-jdbc数据源,那是springboot官方推荐的数据源(质量和并发性都很好)
  • 遵照数据源生成SqlSessionFactory
    • 值得注意的是,数据源是必须钦赐的,不然springboot运维不了
    • typeAliasesPackage和mapperLocations不是必须的,假使全勤项目不要求动用*Mapper.xml来写SQL的话(即只用表明就足以化解),那么不须要配
  • @Primary声明:钦赐在同三个接口有八个完成类可以注入的时候,暗中认可选项哪贰个,而不是让@Autowire注解报错(1般用来多数据源,五个SqlSessionFactory的动静下)

那般之后,在品种中再使用springboot就和在ssm中(配置达成后)使用同样了。

 

5、com.xxx.firstboot.mapper.UserMapper

图片 10 1 package
com.xxx.firstboot.mapper; 2 3 import
org.apache.ibatis.annotations.Insert; 4 import
org.apache.ibatis.annotations.Param; 5 6 import
com.xxx.firstboot.domain.User; 7 8 public interface UserMapper { 9 10
@Insert(“INSERT INTO tb_user(username, password)
VALUES(#{username},#{password})”) 11 public int
insertUser(@Param(“username”) String username, @Param(“password”) String
password); 12 13 /** 14 * 插入用户,并将主键设置到user中 一5 *
注意:重临的是数据库影响条数,即一 1陆 */ 17 public int
insertUserWithBackId(User user); 18 } View Code

表明:该接口中有七个点子,

  • 多个平淡无奇插入:间接用注明化解
  • 2个安排重临主键:需求接纳xml来消除

图片 11 1 <?xml
version=”1.0″ encoding=”UTF-8″ ?> 2 <!DOCTYPE mapper PUBLIC
“-//mybatis.org//DTD Mapper 3.0//EN”
“; 3 4 <!–
钦赐工作空间,要与接口名相同,源代码未有去看,估摸应该是经过”那里的namespace.上边方法的id”来恒定方法的
–> 伍 <mapper namespace=”com.xxx.firstboot.mapper.UserMapper”>
6 7 <!– 若不须要活动回到主键,将useGeneratedKeys=”true”
keyProperty=”id”去掉即可(当然假如不须要活动回到主键,直接用评释即可)
–> 8 <insert id=”insertUserWithBackId” parameterType=”User”
useGeneratedKeys=”true” keyProperty=”id” > 玖 <![CDATA[ 10 INSERT
INTO tb_user 11 ( 12 username, 13 password 14 ) 15 VALUES 16 ( 17
#{username, jdbcType=VARCHAR}, 18 #{password, jdbcType=VARCHAR} 19 )
20 ]]> 21 </insert> 22 23 </mapper> View Code

 

6、com.xxx.firstboot.dao.UserDao

图片 12 1 package
com.xxx.firstboot.dao; 2 3 import
org.springframework.beans.factory.annotation.Autowired; 4 import
org.springframework.stereotype.Repository; 5 6 import
com.xxx.firstboot.domain.User; 7 import
com.xxx.firstboot.mapper.UserMapper; 8 9 @Repository 10 public class
UserDao { 11 12 @Autowired 13 private UserMapper userMapper; 14 15
public int insertUser(String username, String password){ 16 return
userMapper.insertUser(username, password); 17 } 18 19 public int
insertUserWithBackId(User user){ 20 return
userMapper.insertUserWithBackId(user); 21 } 22 23 } View Code

 

7、com.xxx.firstboot.service.UserService

图片 13 一 package
com.xxx.firstboot.service; 2 叁 import
org.springframework.beans.factory.annotation.Autowired; 4 import
org.springframework.stereotype.Service; 5 陆 import
com.xxx.firstboot.dao.UserDao; 七 import com.xxx.firstboot.domain.User; 8
九 @Service 10 public class UserService { 1一 1二 @Autowired 一三 private
UserDao userDao; 1肆 1五 public boolean addUser(String username, String
password){ 1陆 return userDao.insertUser(username,
password)==壹?true:false; 一柒 } 18 19 public User addUserWithBackId(String
username, String password){ 20 User user = new User(); 2一user.setUsername(username); 2二 user.setPassword(password); 二三userDao.insertUserWithBackId(user);//该措施后,主键已经安装到user中了 二四return user; 25 } 二陆 贰七 } View
Code

 

8、com.xxx.firstboot.controller.UserController

图片 14 1 package
com.xxx.firstboot.web; 二 3 import
org.springframework.beans.factory.annotation.Autowired; 四 import
org.springframework.web.bind.annotation.RequestMapping; 5 import
org.springframework.web.bind.annotation.RequestMethod; 陆 import
org.springframework.web.bind.annotation.RequestParam; 七 import
org.springframework.web.bind.annotation.RestController; 八 九 import
com.xxx.firstboot.domain.User; 十 import
com.xxx.firstboot.service.UserService; 1壹 1二 import
io.swagger.annotations.Api; 13 import
io.swagger.annotations.ApiImplicitParam; 14 import
io.swagger.annotations.ApiImplicitParams; 15 import
io.swagger.annotations.ApiOperation; 1六 import
io.swagger.annotations.ApiResponse; 17 import
io.swagger.annotations.ApiResponses; 18 1九 @RestController 20
@RequestMapping(“/user”) 贰1 @Api(“userController相关api”) 2二 public
class UserController { 二三 二四 @Autowired 二5 private UserServiceuserService; 二陆 二柒 @ApiOperation(“添加用户”) 28 @ApiImplicitParams({ 2九@ApiImplicitParam(paramType=”query”,name=”username”,dataType=”String”,required=true,value=”用户的真名”,defaultValue=”zhaojigang”),
30
@ApiImplicitParam(paramType=”query”,name=”password”,dataType=”String”,required=true,value=”用户的密码”,defaultValue=”wangna”)
3一 }) 3二 @ApiResponses({ 33@ApiResponse(code=400,message=”请求参数没填好”), 34@ApiResponse(code=40四,message=”请求路径未有或页面跳转路径不对”) 35 }) 36@RequestMapping(value=”/addUser”,method=RequestMethod.POST) 3七 public
boolean addUser(@RequestParam(“username”) String username, 3捌@RequestParam(“password”) String password) { 3九 return
userService.addUser(username,password); 40 } 肆1 4二@ApiOperation(“添加用户且重返已经设置了主键的user实例”) 43@ApiImplicitParams({ 44@ApiImplicitParam(paramType=”query”,name=”username”,dataType=”String”,required=true,value=”用户的姓名”,defaultValue=”zhaojigang”),
45@ApiImplicitParam(paramType=”query”,name=”password”,dataType=”String”,required=true,value=”用户的密码”,defaultValue=”wangna”)
4陆 }) 4七 @ApiResponses({ 4八@ApiResponse(code=400,message=”请求参数没填好”), 4九@ApiResponse(code=40四,message=”请求路径未有或页面跳转路径不对”) 50 }) 5一@RequestMapping(value=”/addUserWithBackId”,method=RequestMethod.POST) 5二public User addUserWithBackId(@RequestParam(“username”) String username,
伍三 @RequestParam(“password”) String password) { 5四 return
userService.addUserWithBackId(username, password); 55 } 5陆 } View Code

 

测试:

进入项指标pom.xml文件所在目录,执行”mvn
spring-boot:run”(那是最推荐的spring-boot的运维格局),别的1种在主类上右击–>”run
as”–>”java application”不常用

springboot + mybatis,springbootmybatis
springboot集成了springJDBC与JPA,然则并没有集成mybatis,所以想要使用mybatis就要和谐去集成。集成格局13分…

一.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

 

<groupId>io.springfox</groupId>

二.三 创制生成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>标签配置1致

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 汉化


private String userNo;

三.贰 更详尽的汉化

设若想进一步调动译文,能够在META-INF\resources\webjars\springfox-swagger-ui\lang
目录下添加zh-cn.js文件.

图片 15

 

然后在译文(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”:”服务器重返”

});

劳苦功高告成!

count =
service.deleteByPrimaryKey(id);

Swagger二在SpringBoot环境下的行使

@ApiImplicitParams({

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
出现40肆时能够把注释去掉试试

// * 消除财富系统财富目录与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())//公共参数

.select()

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

.paths(PathSelectors.any())

.build();

}

 

private ApiInfo apiInfo()
{

return new ApiInfoBuilder()

.title(“Demo APIs”)

.description(“应用实例”)

//.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
}

}

 

@ApiOperation(value =
“添加用户消息”, notes = “添加用户新闻”)

壹.三 申明使用

成效范围

API

运用地方

对象属性

@ApiModelProperty

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

协议集讲述

@Api

用于controller类上

探讨描述

@ApiOperation

用在controller的措施上

Response集

@ApiResponses

用在controller的不2法门上

Response

@ApiResponse

用在 @ApiResponses里边

非对象参数集

@ApiImplicitParams

用在controller的法子上

非对象参数描述

@ApiImplicitParam

用在@ApiImplicitParams的秘籍里边

叙述重返对象的含义

@ApiModel

用在回去对象类上

ApiImplicitParam的有关属性

属性

取值

作用

paramType

path

query

body

header

form

参数放在哪个地点:必须求有其1本性

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 = “更新用户名称和年龄”)

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

}

}

 

@EnableSwagger2 //
启用Swagger2

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
可能HTML伍–>

<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>

 

 

return “error.jsp”;

1. 集成Swagger

}

二. 变型静态API文书档案pdf

return “error.jsp”;

叁.1 添加自定义首页和译文

在resourece目录下开创\META-INF\resourece目录,然后成立二个名号为”swagger-ui.html”
的HTML文件

图片 16

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-32×32.png” sizes=”32×32″/>

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

<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 看看展现效果:

图片 17

</dependency>

2.2 创建index.adoc文件

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

内容:

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

 

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

1.4 访问控制台

 

按以下步骤配置,项目运维后走访:

e.getMessage();

*/

</dependency>

.withMethodAnnotation(ApiOperation.class))

.termsOfServiceUrl(“”)

/**

}

* 注脚:@Date提姆eFormat 和 @JsonFormat
用于在吸收和再次回到日期格式时将其格式化 实体类对应的数据表为:
user_info

@ApiModel(value = “UserInfo”)

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

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

}

<version>2.6.1</version>

<groupId>com.github.xiaoymin</groupId>

*/

int count = 0;

import
javax.servlet.http.HttpServletRequest;

经过@Configuration证明,注脚它是贰个安插类,@EnableSwagger二开启swagger二。apiINfo()配置部分主导的消息。apis()钦点扫描的包会生成文书档案。

import
springfox.documentation.builders.RequestHandlerSelectors;

private String userPhone;

if(count <=0 ) {

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

@ApiModelProperty(value =
“记录修改时间”)

源码下载地址:

</dependency>

@Api(value = “UserInfo”,
description = “人士基本音信 “)

6、替换暗许的UI

//
扫描内定包中的swagger注脚

@JsonFormat(locale = “zh”, timezone =
“GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)

swagger通过注明阐明该接口会转变文书档案,包罗接口名、请求方法、参数、重临音讯的等等。

@RequestMapping(value =
“deleteById”, method = RequestMethod.GET)

<dependency>

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

五、运行程序访问
http://localhost:8080/spring-mvc/swagger-ui.html

<dependency>

<groupId>io.springfox</groupId>

<version>2.6.1</version>

<artifactId>springfox-swagger2</artifactId>

}

<artifactId>jackson-databind</artifactId>

private String password;

return
“userView.jsp”;

<dependency>

import
io.swagger.annotations.ApiModel;

@RequestMapping(value =
“update”, method = RequestMethod.POST)

参考资料

购并步骤

import
io.swagger.annotations.ApiImplicitParams;

https://gitee.com/xiaoym/swagger-bootstrap-ui

import
com.fasterxml.jackson.annotation.JsonIgnoreProperties;