Swagger2在SpringBoot环境下的利用,RESTful风格的Web服务框架

by admin on 2019年2月25日

Swagger2在SpringBoot环境下的行使

合并步骤

第五章 springboot + mybatis,springbootmybatis

springboot集成了springJDBC与JPA,不过并未集成mybatis,所以想要使用mybatis就要和谐去集成。集成方式卓越简单。

壹 、项目协会

bf88必发唯一官网 1

 

2、pom.xml

bf88必发唯一官网 2 1 <!–
与数据库操作相关的依靠 –> 2 <dependency> 3
<groupId>org.springframework.boot</groupId> 4
<artifactId>spring-boot-starter-jdbc</artifactId> 5
</dependency> 6 7 <!– 使用数据源 –> 8 <dependency> 9
<groupId>com.alibaba</groupId> 10
<artifactId>druid</artifactId> 11
<version>1.0.14</version> 12 </dependency> 13 14
<!– 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

bf88必发唯一官网 31
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集成的输入

bf88必发唯一官网 4 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 * 1)创建数量源 21 *
2)创建SqlSessionFactory 22 *Swagger2在SpringBoot环境下的利用,RESTful风格的Web服务框架。/ 23 @Configuration
//该注脚类似于spring配置文件 24
@MapperScan(basePackages=”com.xxx.firstboot.mapper”) 25 public class
MyBatisConfig { 26 27 @Autowired 28 private Environment env; 29 30 /**
31 * 创设数量源 32 * @Primary
该评释热示在同一个接口有多少个落实类能够注入的时候,私下认可选项哪五个,而不是让@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 47 */ 48 @Bean 49 public
SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{ 50
SqlSessionFactoryBean fb = new SqlSessionFactoryBean(); 51
fb.setDataSource(ds);//钦点数据源(这些必须有,不然报错) 52
//上面两句仅仅用于*.xml文件,要是全勤持久层操作不须要使用到xml文件的话(只用注脚就足以解决),则不加
53
fb.setTypeAliasesPackage(env.getProperty(“mybatis.typeAliasesPackage”));//钦定基包
54 fb.setMapperLocations(new
PathMatchingResourcePatternResolver().getResources(env.getProperty(“mybatis.mapperLocations”)));//钦点xml文件地点55 56 return fb.getObject(); 57 } 58 59 } View Code

说明:

  • 类上面添加三个
    • @Configuration表明(该注脚类似于spring的安排文件)
    • @MapperScan注脚,钦定扫描的mapper接口所在的包
  • 在此类中,注入了Environment实例,使用该实例能够去读取类路径下application.properties文件中的内容,读取文件内容的二种办法,见第一章
    第四个spring-boot程序
  • 在此类中,使用druid数据源定义了数据源Bean,spring-boot暗许使用的是tomcat-jdbc数据源,那是springboot官方推荐的数据源(质量和并发性都很好)
  • 据悉数据源生成SqlSessionFactory
    • 值得注意的是,数据源是必须内定的,否则springboot运转不了
    • typeAliasesPackage和mapperLocations不是必须的,假若整个项目不必要选用*Mapper.xml来写SQL的话(即只用证明就能够化解),那么不须求配
  • @Primary评释:钦点在同3个接口有五个落到实处类能够注入的时候,暗许选项哪二个,而不是让@Autowire注解报错(一般用来多数据源,多少个SqlSessionFactory的情形下)

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

 

5、com.xxx.firstboot.mapper.UserMapper

bf88必发唯一官网 5 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中 15 *
注意:再次回到的是数据库影响条数,即1 16 */ 17 public int
insertUserWithBackId(User user); 18 } View Code

证实:该接口中有七个形式,

  • 3个熟视无睹插入:直接用声明化解
  • 2个安插再次回到主键:供给选拔xml来解决

bf88必发唯一官网 6 1 <?xml
version=”1.0″ encoding=”UTF-8″ ?> 2 <!DOCTYPE mapper PUBLIC
“-//mybatis.org//DTD Mapper 3.0//EN”
“; 3 4 <!–
内定工作空间,要与接口名相同,源代码没有去看,测度应该是透过”那里的namespace.上面方法的id”来定位方法的
–> 5 <mapper namespace=”com.xxx.firstboot.mapper.UserMapper”>
6 7 <!– 若不须求活动重回主键,将useGeneratedKeys=”true”
keyProperty=”id”去掉即可(当然借使不要求活动重临主键,直接用申明即可)
–> 8 <insert id=”insertUserWithBackId” parameterType=”User”
useGeneratedKeys=”true” keyProperty=”id” > 9 <![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

bf88必发唯一官网 7 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

bf88必发唯一官网 8 1 package
com.xxx.firstboot.service; 2 3 import
org.springframework.beans.factory.annotation.Autowired; 4 import
org.springframework.stereotype.Service; 5 6 import
com.xxx.firstboot.dao.UserDao; 7 import com.xxx.firstboot.domain.User; 8
9 @Service 10 public class UserService { 11 12 @Autowired 13 private
UserDao userDao; 14 15 public boolean addUser(String username, String
password){ 16 return userDao.insertUser(username,
password)==1?true:false; 17 } 18 19 public User addUserWithBackId(String
username, String password){ 20 User user = new User(); 21
user.setUsername(username); 22 user.setPassword(password); 23
userDao.insertUserWithBackId(user);//该措施后,主键已经设置到user中了 24
return user; 25 } 26 27 } View
Code

 

8、com.xxx.firstboot.controller.UserController

bf88必发唯一官网 9 1 package
com.xxx.firstboot.web; 2 3 import
org.springframework.beans.factory.annotation.Autowired; 4 import
org.springframework.web.bind.annotation.RequestMapping; 5 import
org.springframework.web.bind.annotation.RequestMethod; 6 import
org.springframework.web.bind.annotation.RequestParam; 7 import
org.springframework.web.bind.annotation.RestController; 8 9 import
com.xxx.firstboot.domain.User; 10 import
com.xxx.firstboot.service.UserService; 11 12 import
io.swagger.annotations.Api; 13 import
io.swagger.annotations.ApiImplicitParam; 14 import
io.swagger.annotations.ApiImplicitParams; 15 import
io.swagger.annotations.ApiOperation; 16 import
io.swagger.annotations.ApiResponse; 17 import
io.swagger.annotations.ApiResponses; 18 19 @RestController 20
@RequestMapping(“/user”) 21 @Api(“userController相关api”) 22 public
class UserController { 23 24 @Autowired 25 private UserServiceuserService; 26 27 @ApiOperation(“添加用户”) 28 @ApiImplicitParams({ 29
@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”)
31 }) 32 @ApiResponses({ 33
@ApiResponse(code=400,message=”请求参数没填好”), 34
@ApiResponse(code=404,message=”请求路径没有或页面跳转路径不对”) 35 }) 36
@RequestMapping(value=”/addUser”,method=RequestMethod.POST) 37 public
boolean addUser(@RequestParam(“username”) String username, 38
@RequestParam(“password”) String password) { 39 return
userService.addUser(username,password); 40 } 41 42
@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”)
46 }) 47 @ApiResponses({ 48
@ApiResponse(code=400,message=”请求参数没填好”), 49
@ApiResponse(code=404,message=”请求路径没有或页面跳转路径不对”) 50 }) 51
@RequestMapping(value=”/addUserWithBackId”,method=RequestMethod.POST) 52
public User addUserWithBackId(@RequestParam(“username”) String username,
53 @RequestParam(“password”) String password) { 54 return
userService.addUserWithBackId(username, password); 55 } 56 } View Code

 

测试:

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

springboot + mybatis,springbootmybatis
springboot集成了springJDBC与JPA,可是没有集成mybatis,所以想要使用mybatis就要协调去集成。集成方式相当…

Swagger与SpringMVC项目组成

为了方便的管制项目中API接口,在网上找了重重关于API接口管理的素材,感觉近日最风靡的莫过于Swagger了,效用强大,UI界面美丽,并且援救在线测试等等,所以小编仔细研讨了下Swagger的利用,下面就如何将Swagger与私家的SpringMVC项目展开整合做详细表明:

说到底API管理界面: 
bf88必发唯一官网 10

详细步骤:

1. 集成Swagger

壹 、在pom.xml中引费用swagger重视包

Step1:项目中引入相关jar包:

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.spring>3.2.9.RELEASE</version.spring>
        <version.jackson>2.4.4</version.jackson>
    </properties>

    <dependencies>
        ....
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>0.9.5</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${version.jackson}</version>
        </dependency>
    </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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>

Step2:添加自定义config文件

package com.spg.apidoc.common.configer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;

/**
 * 项目名称:apidoc
 *
 * @description:
 * @author Wind-spg
 * @create_time:2015年2月10日 上午10:27:51
 * @version V1.0.0
 *
 */
@Configuration
@EnableSwagger
// Loads the spring beans required by the framework
public class MySwaggerConfig
{

    private SpringSwaggerConfig springSwaggerConfig;

    /**
     * Required to autowire SpringSwaggerConfig
     */
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)
    {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    /**
     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
     * framework - allowing for multiple swagger groups i.e. same code base
     * multiple swagger resource listings.
     */
    @Bean
    public SwaggerSpringMvcPlugin customImplementation()
    {
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(
                ".*?");
    }

    private ApiInfo apiInfo()
    {
        ApiInfo apiInfo = new ApiInfo(
                "My Apps API Title", 
                "My Apps API Description",
                "My Apps API terms of service", 
                "My Apps API Contact Email", 
                "My Apps API Licence Type",
                "My Apps API License URL");
        return apiInfo;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

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())//公共参数

.select()

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

.paths(PathSelectors.any())

.build();

}

 

private ApiInfo apiInfo()
{

return new ApiInfoBuilder()

Swagger2在SpringBoot环境下的利用,RESTful风格的Web服务框架。.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
}

}

 

<groupId>io.springfox</groupId>

Step3:将此布局加入到Spring容器中,如下:

<bean class="com.spg.apidoc.common.configer.MySwaggerConfig" />
  • 1

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-宝马X3S的环境,只好利用 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;

}

}

 

<artifactId>springfox-swagger2</artifactId>

Step4:在代码中添加相关APIAnnotation,如下:

    @ResponseBody
    @RequestMapping(
            value = "addUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "添加用户", httpMethod = "POST", response = BaseResultVo.class, notes = "add user")
    public String addUser(@ApiParam(required = true, name = "postData", value = "用户信息json数据") @RequestParam(
            value = "postData") String postData, HttpServletRequest request)
    {
        LOGGER.debug(String.format("at function, %s", postData));
        if (null == postData || postData.isEmpty())
        {
            return super.buildFailedResultInfo(-1, "post data is empty!");
        }

        UserInfo user = JSON.parseObject(postData, UserInfo.class);
        int result = userService.addUser(user);
        return buildSuccessResultInfo(result);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

说明: 
其间@ApiOperation和@ApiParam为增进的API相关心解,个参数表明如下: 
@ApiOperation(value = “接口表达”, httpMethod = “接口请求格局”,
response = “接口再次回到参数类型”, notes =
“接口公布表明”;其余参数可参看源码; 
@ApiParam(required = “是不是必须参数”, name = “参数名称”, value =
“参数具体讲述”

1.4 访问控制台

 

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

<version>2.6.1</version>

Step5:添加Swagger UI配置

在GitHub上下载SwaggerUI项目,将dist下拥有内容拷贝到本地品种webapp下边,结果目录如下图所示: 
bf88必发唯一官网 11

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>

Step6:修改index.html

将index.html中修改为{projectname}/api-docs

到此截至,全数配置实现,运行你的项目,访问{projectName}/index.html即可看出如下所示页面: 
bf88必发唯一官网 12
bf88必发唯一官网 13

项目最后demo可知个人GitHub 
 
参考: 
 

项目jar包下载:

 

 

       
当我们把我们的劳务以REST的方式接口暴表露来,其余开发者要调用大家的接口首先要力所能及详细的理解大家的API,方今差不离全数的开放平台都以把API以文书档案的情势放在网站上,例如:果壳网、Tmall、微信等等。

在开发者调用API在此之前对一些API表达的知道相比模糊,总想着能直接证实一下投机的通晓就好了,而不是索要去档次写测试代码来验证本身的想法。即API文书档案应负有直接实施能力。Swagger便是这么的多个利器,Swagger
是二个专业和总体的框架,用于转移、描述、调用和可视化 RESTful 风格的 Web
服务。总体指标是使客户端和文件系统作为服务器以同等的快慢来更新。文件的章程,参数和模型紧凑集成到劳动器端的代码,允许API来始终维持同步。Swagger
让铺排管理和运用效用强大的API从未如此简约。

 

上面说一下如何为依存项目增加Swagger

首先添加对Swagger的信赖

<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core_2.10</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.0</version>
</dependency>

进入对Swagger的配置类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import com.wordnik.swagger.model.ApiInfo;

@Configuration
@EnableSwagger
public class MySwaggerConfig {
private SpringSwaggerConfig
springSwaggerConfig;

/**
* Required to autowire SpringSwaggerConfig
*/
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig
springSwaggerConfig) {
this.springSwaggerConfig =
springSwaggerConfig;
}

/**
* Every SwaggerSpringMvcPlugin bean is picked up by
the swagger-mvc framework – allowing for multiple
* swagger groups i.e. same code base multiple
swagger resource listings.
*/
@Bean
public SwaggerSpringMvcPlugin
customImplementation(){
SwaggerSpringMvcPlugin ssmp = new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.swaggerGroup(“api-docs”).build();
return ssmp;
}

private ApiInfo apiInfo() {
ApiInfo apiInfo
= new ApiInfo(
“tk API SPECIFICATION”,
“This is the tk api
specification,here you can dig into the details of api and do api
testing as well.”,
“”,
“”,
“”,
“”);
return
apiInfo;
}
}

在application.xml中加进铺排:

<mvc:annotation-driven/>
<bean id=”apiDoc” class=”com.tk.framework.rest.framework.swaggerconfig.MySwaggerConfig”/>
<!– Enable scanning of spring
@Configuration classes –>
<context:annotation-config/>
<!– Enable the default
documentation controller–>
<context:component-scan base-package=”com.mangofactory.swagger.controllers”/>

<!– Pick up the bundled spring
config–>
<context:component-scan base-package=”com.mangofactory.swagger.configuration”/>

进而,给开放API的Resource类加上API
Annotation,那样上一步配置的Scanner就可见扫描到该Resource开放的API了。 

@RestController
@RequestMapping(value = “/1/users”)
@Api(value = “User”, description = “User service api”, position = 1)
public class UserResourceV1 extends BaseResources
{
private static final Logger logger = LoggerFactory.getLogger(UserResourceV1.class);
@Autowired
private UserService userService;

@ResourceDescription(Resource=”user”, Operation=”getUser”)
@RequestMapping(value = “/{id}”, method = RequestMethod.GET)
@ApiOperation(httpMethod = “GET”, nickname=”getUser”, value = “get user by userId”)
public ResponseModel getUser(@ApiParam(value = “id for greeting”,
required = true)@PathVariable String id) throws RestException
{
UserModel u = null;
try
{
u =
userService.findById(id);
}
catch (Exception e)
{
logger.error(e.getMessage());
throw new RestException(e.getMessage());
}
ResponseModel r
= new ResponseModel();
r.setStatus(200);
r.setResult(u);
return r;
}

}

为Model添加Swagger的Annotation,那样Swagger
Scanner能够得到更加多关于Model对象的新闻。 :

@ApiModel(value=”User”)
@Entity
@Table(name = “user”)
public class UserModel {
/**
* id
*/
@ApiModelProperty(required = true)
private String id;
/**
* 姓名
*/
@ApiModelProperty(required = true)
private String name;
/**
* 年龄
*/
@ApiModelProperty(required = true,
allowableValues=”range[1,100]”)
private Integer age;
/**
* 性别
*/
@ApiModelProperty(required = true,
allowableValues = “F,M”)
private String sex;
@ApiModelProperty(required = true)
private String password;

……

在Swagger Annotation中:

 

    @API表示2个怒放的API,能够因而description简要描述该API的机能。

   
在3个@API下,可有八个@ApiOperation,表示针对该API的CRUD操作。在ApiOperation
Annotation中能够经过value,notes描述该操作的作用,response描述平日景况下该请求的回到对象类型。

   
在七个ApiOperation下,能够透过ApiResponses描述该API操作大概出现的卓殊景况。

    @ApiParam用于描述该API操作接受的参数类型

 

接下去,我们把那个音讯和Swagger
UI集成,以尤其美观,实用的方式把这么些API新闻展现出来。 

首先,从github(,
把该品种dist目录下的始末拷贝到项指标webapp的目录下。 

bf88必发唯一官网 14

 

 然后,修改index.jsp, 把Swagger UI对象中的U奥德赛L替换为协调的API路径:

window.swaggerUi
= new SwaggerUi({
url: “/api/api-docs”,
dom_id: “swagger-ui-container”,

运转项目,最终如下图所示:

 

bf88必发唯一官网 15

 

 

bf88必发唯一官网 16

 

bf88必发唯一官网 17

 

 具有直接测试API的能力:

bf88必发唯一官网 18

  

 

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-INF\resourece目录,然后创造三个称呼为”swagger-ui.html”
的HTML文件

bf88必发唯一官网 19

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

bf88必发唯一官网 20

</dependency>

3.2 更详尽的汉化

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

bf88必发唯一官网 21

 

接下来在译文(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()钦点扫描的包会生成文书档案。

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

*

*

*/

@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonIgnoreProperties({ “handler”,
“hibernateLazyInitializer” })

@ApiModel(value = “UserInfo”)

public class UserInfo {

@ApiModelProperty(value = “ID”)

private Integer id;

@ApiModelProperty(value = “用户登录账号”,
required = true)

private String userNo;

@ApiModelProperty(value = “姓名”, required
= true)

private String userName;

@ApiModelProperty(value =
“姓名拼音”)

private String spellName;

@ApiModelProperty(value = “密码”, required
= true)

private String password;

@ApiModelProperty(value = “手机号”,
required = true)

private String userPhone;

@ApiModelProperty(value = “性别”)

private Integer userGender;

@ApiModelProperty(value =
“记录创造时间”)

@DateTimeFormat(pattern = “yyyy-MM-dd
HH:mm:ss”)

private Date createTime;

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

@DateTimeFormat(pattern = “yyyy-MM-dd
HH:mm:ss”)

private Date updateTime;

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

public Date getCreateTime() {

return createTime;

}

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

public Date getUpdateTime() {

return updateTime;

}

}

④ 、控制器类

package
com.vk.liyj.controller;

import
io.swagger.annotations.Api;

import
io.swagger.annotations.ApiImplicitParam;

import
io.swagger.annotations.ApiImplicitParams;

import
io.swagger.annotations.ApiOperation;

import
java.util.List;

import
javax.servlet.http.HttpServletRequest;

import
javax.servlet.http.HttpServletResponse;

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

import
org.springframework.stereotype.Controller;

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

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

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

import
com.vk.liyj.model.UserInfo;

import
com.vk.liyj.service.UserInfoService;

/**

* 类描述:职员基本消息

*/

@Controller

@RequestMapping(value =
“/userInfo”)

@Api(value = “UserInfo”,
description = “人士为主新闻 “)

public class
UserInfoController {

@Autowired

UserInfoService
service;

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

@ApiOperation(value =
“查询全部的人士音讯”, notes = “查询全体的人口新闻”)

public String
selectAllUsers(HttpServletRequest request, HttpServletResponse response)
{

List<UserInfo>
userList = service.selectAllUsers();

request.setAttribute(“userList”,
userList);

return
“userList.jsp”;

}

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

@ApiOperation(value =
“依据用户id查询用户详细音讯”, notes =
“依据用户id查询用户详细消息”)

@ApiImplicitParams({

@ApiImplicitParam(name =
“type”, value = “类型(修改:update;私下认可为查看)”, required = false,
paramType = “query”),

@ApiImplicitParam(name =
“id”, value = “用户id”, required = true, paramType = “query”)

})

public String
selectById(HttpServletRequest request, HttpServletResponse
response,

@RequestParam(value = “id”)
Integer id, @RequestParam(value = “type”) String type) {

UserInfo user =
service.selectByPrimaryKey(id);

request.setAttribute(“user”,
user);

if(“update”.equals(type))
{

return
“userUpdate.jsp”;

} else {

return
“userView.jsp”;

}

}

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

@ApiOperation(value =
“根据用户id删除用户音信”, notes = “遵照用户id删除用户音信”)

@ApiImplicitParams({

@ApiImplicitParam(name =
“id”, value = “用户id”, required = true, paramType = “query”)

})

public String
deleteById(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = “id”) Integer id) {

int count = 0;

try {

count =
service.deleteByPrimaryKey(id);

if(count <=0 ) {

return “error.jsp”;

} else {

request.getRequestDispatcher(“selectAllUsers”).forward(request,
response);

return
“userList.jsp”;

}

} catch (Exception e)
{

e.getMessage();

e.printStackTrace();

return “error.jsp”;

}

}

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

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

bf88必发唯一官网 ,public String
add(HttpServletRequest request, HttpServletResponse response, UserInfo
user) {

int count = 0;

try {

count =
service.insertSelective(user);

if(count <=0 ) {

return “error.jsp”;

} else {

//POST请求的措施不可能直接倒车到GET请求的艺术,需求重定向

response.sendRedirect(“selectAllUsers”);

return
“userList.jsp”;

}

} catch (Exception e)
{

e.getMessage();

e.printStackTrace();

return “error.jsp”;

}

}

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

@ApiOperation(value =
“根据用户id修改用户音信”, notes = “依据用户id修改用户消息”)

public String
update(HttpServletRequest request, HttpServletResponse response,
UserInfo user) {

int count = 0;

try {

count =
service.updateByPrimaryKeySelective(user);

if(count <=0 ) {

return “error.jsp”;

} else {

//POST请求的主意无法直接倒车到GET请求的主意,要求重定向

response.sendRedirect(“selectAllUsers”);

return
“userList.jsp”;

}

} catch (Exception e)
{

e.getMessage();

e.printStackTrace();

return “error.jsp”;

}

}

}

swagger通过注明注解该接口会转移文档,包罗接口名、请求方法、参数、再次来到新闻的等等。

  • @Api:修饰整个类,描述Controller的效能
  • @ApiOperation:描述三个类的2个形式,恐怕说四个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接受参数
  • @ApiProperty:用对象吸收参数时,描述对象的二个字段
  • @ApiResponse:HTTP响应当中二个描述
  • @ApiResponses:HTTP响应全部描述
  • @ApiIgnore:使用该评释忽略这么些API
  • @ApiError :发生错误重回的音讯
  • @ApiParamImplicitL:一个伸手参数
  • @ApiParamsImplicit 七个请求参数

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

六 、替换暗许的UI

<dependency>

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

<artifactId>swagger-bootstrap-ui</artifactId>

<version>1.6</version>

</dependency>

<!–
使用swagger-bootstrap-ui替换默许的UI

<dependency>

<groupId>io.springfox</groupId>

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

<version>2.6.1</version>

</dependency>

–>

轮换后走访路径:http://localhost:8080/web/doc.html

参考资料

http://blog.csdn.net/songanling/article/details/71079304

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

源码下载地址:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图