您的位置:1010cc时时彩经典版 > 1010cc时时彩经典版 > 1010cc时时彩经典版SpringBoot学习笔记之集成swagge

1010cc时时彩经典版SpringBoot学习笔记之集成swagge

发布时间:2019-12-01 20:18编辑:1010cc时时彩经典版浏览(156)

    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)卡塔尔(英语: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("应用实例"卡塔尔(قطر‎

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

    }

     

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

    第四章 springboot swagger,springbootswagger

    注:本文参谋自

     

    swagger用于定义API文书档案。

    好处:

    • 左右端抽离开荒
    • API文书档案特别令人侧目
    • 测量检验的时候不须求再利用U途锐L输入浏览器的章程来探访Controller
    • 历史观的输入U本田CR-VL的测量试验方法对于post央求的传参比较麻烦(当然,能够应用postman那样的浏览器插件)
    • spring-boot与swagger的购并轻便的大器晚成逼

    1、项目布局

    和上后生可畏节同样,没有改动。

    2、pom.xml

    引进了八个jar。

    1010cc时时彩经典版 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

    1010cc时时彩经典版 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

    1010cc时时彩经典版 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"卡塔尔(英语:State of Qatar) 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卡塔尔(قطر‎ 41 public User getUser(@RequestHeader("username"卡塔尔 String username, @RequestParam("password"卡塔尔 String password卡塔尔(英语:State of Qatar) { 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.USERAV4_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:抛出十二分的类

    如上这一个正是最常用的多少个表明了。

    具体其余的批注,查看:

     

    测试:

    起步服务,浏览器输入""

    1010cc时时彩经典版 4

    最上部三个红框:@Api

    GET红框:method=RequestMethod.GET

    左边红框:@ApiOperation

    parameter红框:@ApiImplicitParams体系表明

    response messages红框:@ApiResponses类别阐明

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

    1010cc时时彩经典版 5

     

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

    第五章 springboot mybatis,springbootmybatis

    springboot集成了springJDBC与JPA,不过从未集成mybatis,所以想要使用mybatis就要团结去集成。集成情势非常轻巧。

    1、项目结构

    1010cc时时彩经典版 6

     

    2、pom.xml

    1010cc时时彩经典版 7 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

    1010cc时时彩经典版 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集成的入口

    1010cc时时彩经典版 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 * 1)成立数量源 21 * 2)创建SqlSessionFactory 22 */ 23 @Configuration //该注明相同于spring配置文件 24 @MapperScan(basePackages="com.xxx.firstboot.mapper"卡塔尔(英语:State of Qatar) 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"卡塔尔(英语:State of Qatar)卡塔尔国;//钦定基包 54 fb.setMapperLocations(new PathMatchingResourcePatternResolver(卡塔尔国.getResources(env.getProperty("mybatis.mapperLocations"卡塔尔(英语:State of Qatar)卡塔尔(英语:State of Qatar)卡塔尔(英语:State of Qatar);//钦点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运转不了
      • type阿里asesPackage和mapperLocations不是必得的,要是一切项目无需使用*Mapper.xml来写SQL的话(即只用评释就能够消除),那么无需配
    • @Primary评释:钦点在同四个接口有多少个贯彻类能够注入的时候,默许选项哪三个,实际不是让@Autowire申明报错(日常用来非常多据源,三个SqlSessionFactory的情状下)

    如此那般以往,在类型中再利用springboot就和在ssm中(配置达成后)使用同一了。

     

    5、com.xxx.firstboot.mapper.UserMapper

    1010cc时时彩经典版 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中 15 * 注意:重回的是数据库影响条数,即1 16 */ 17 public int insertUserWithBackId(User user); 18 } View Code

    表达:该接口中有多个章程,

    • 多少个弃之可惜插入:直接用注明化解
    • 叁个陈设重回主键:必要选用xml来消除

    1010cc时时彩经典版 11 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

    1010cc时时彩经典版 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

    1010cc时时彩经典版 13 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

    1010cc时时彩经典版 14 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"卡塔尔(英语:State of Qatar) 21 @Api("userController相关api"卡塔尔(قطر‎ 22 public class UserController { 23 24 @Autowired 25 private UserServiceuser瑟维斯; 26 27 @ApiOperation("增多客户"卡塔尔(英语:State of Qatar) 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="伏乞路线未有或页面跳转路线不对"卡塔尔(英语:State of Qatar) 35 }卡塔尔 36 @RequestMapping(value="/addUser",method=RequestMethod.POST卡塔尔国 37 public boolean addUser(@RequestParam("username"卡塔尔 String username, 38 @RequestParam("password"卡塔尔(英语:State of Qatar) String password卡塔尔 { 39 return userService.addUser(username,password卡塔尔(英语:State of Qatar); 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 }卡塔尔(英语:State of Qatar) 47 @ApiResponses({ 48 @ApiResponse(code=400,message="乞求参数没填好"卡塔尔(英语:State of Qatar), 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卡塔尔(英语:State of Qatar); 55 } 56 } View Code

     

    测试:

    步向项指标pom.xml文件所在目录,施行"mvn spring-boot:run"(那是最推荐的spring-boot的运市价势),其它意气风发种在主类上右击-->"run as"-->"java application"不时用

    springboot mybatis,springbootmybatis springboot集成了springJDBC与JPA,不过未有集成mybatis,所以想要使用mybatis将在和睦去集成。集成格局卓绝...

    Step6:修改index.html

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

    到此甘休,全数配置完结,运营你的类型,访谈{projectName}/index.html就可以知到如下所示页面: 
    1010cc时时彩经典版 15
    1010cc时时彩经典版 16

    花色最后demo可知个人GitHub 
     
    参考: 
     

    项目jar包下载:

     

     

            当大家把大家的服务以REST的样式接口暴流露来,别的开荒者要调用我们的接口首先要能够详细的问询大家的API,这两天大致全部的开放平台都以把API以文书档案的款型放在网址上,比如:搜狐、天猫商城、Wechat等等。

    在开拓者调用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表示二个怒放的API,能够经过description简要描述该API的功能。

        在贰个@API下,可有八个@ApiOperation,表示针对该API的CRUD操作。在ApiOperation Annotation中得以由此value,notes描述该操作的效劳,response描述符合规律情状下该央浼的回到对象类型。

        在四个ApiOperation下,能够经过ApiResponses描述该API操作大概现身的极度意况。

        @ApiParam用于描述该API操作选取的参数类型

     

    接下去,大家把那几个新闻和Swagger UI集成,以这些奇妙,实用的主意把那几个API音信彰显出来。 

    首先,从github(, 把该项目dist目录下的剧情拷贝到项目标webapp的目录下。 

    1010cc时时彩经典版 17

     

     然后,改善index.jsp, 把Swagger UI对象中的UEnclaveL替换为温馨的API路线:

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

    开发银行项目,最终如下图所示:

     

    1010cc时时彩经典版 18

     

     

    1010cc时时彩经典版 19

     

    1010cc时时彩经典版 20

     

     具备直接测量试验API的手艺:

    1010cc时时彩经典版 21

      

     

    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>

     

     

    *

    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

    3.2 更详细的汉化

    尽管想进一层调动译文,能够在META-INFresourceswebjarsspringfox-swagger-uilang 目录下加多zh-cn.js文件.

    1010cc时时彩经典版 22

     

    接下来在译文(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":"服务器再次回到"

    });

    功勋卓著告成!

    import io.swagger.annotations.ApiModel;

    Swagger与SpringMVC项目整合

    为了便于的扣押项目中API接口,在英特网找了过多关于API接口管理的资料,认为近日最流行的实际上Swagger了,作用强大,UI分界面美丽,而且扶植在线测量检验等等,所以小编稳重钻探了下Swagger的施用,上边就怎么着将Swagger与个人的SpringMVC项目进展整合做详细表达:

    谈起底API管理分界面: 
    1010cc时时彩经典版 23

    详尽步骤:

    1. 集成Swagger

    e.getMessage();

    Step5:添加Swagger UI配置

    在GitHub上下载SwaggerUI项目,将dist下具备内容拷贝到本地品种webapp下边,结果目录如下图所示: 
    1010cc时时彩经典版 24

    Swagger2在SpringBoot景况下的利用

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

    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 = “参数具体描述”

    2.2 创建index.adoc文件

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

    内容:

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

     

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

    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.4 访谈调整台

     

    按以下步骤配置,项目运行后寻访:

    e.getMessage();

    Step3:将此安顿参加到Spring容器中,如下:

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

    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

     

    } catch (Exception e) {

    3.1 加多自定义首页和译文

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

    1010cc时时彩经典版 25

    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 看看突显效果:

    1010cc时时彩经典版 26

    try {

    2. 扭转静态API文书档案pdf

    return "error.jsp";

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


    @ApiModelProperty(value = "顾客登陆账号", required = true卡塔尔(英语:State of Qatar)

    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-TiggoS的情状,只可以接纳 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新闻来更新客户详细音信"卡塔尔(英语:State of Qatar)

    @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卡塔尔(英语:State of Qatar) 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"卡塔尔(英语:State of Qatar),

    @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来钦赐删除对象"卡塔尔(英语:State of Qatar)

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

    }

    }

     

    private String password;

    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>

     

    swagger通过申明表明该接口会变卦文书档案,包涵接口名、央浼方法、参数、重临消息的等等。

    private Date createTime;

    <version>2.6.1</version>

    //POST央浼的法子不能够平昔转账到GET诉求的法子,须求重定向

    return "userList.jsp";

    <artifactId>jackson-core</artifactId>

    5、运营程序访谈 http://localhost:8080/spring-mvc/swagger-ui.html

    @ApiOperation(value = "查询全数的职员音信", notes = "查询全体的人口新闻"卡塔尔

    public Date getCreateTime() {

    public Docket createRestApi() {

    }

    <dependency>

    <groupId>io.springfox</groupId>

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

    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

    1010cc时时彩经典版,if("update".equals(type)) {

    private ApiInfo apiInfo() {

    return "userView.jsp";

    return "userList.jsp";

    -->

    return new Docket(DocumentationType.SWAGGER_2)

    * 职员消息表 申明:@ApiModel 和 @ApiModelProperty 用于在经过对象摄取参数时在API文书档案中显得字段的注脚

    }

    @ApiOperation(value = "依照顾客id改革客户音讯", notes = "根据客户id校正客商新闻"卡塔尔(قطر‎

    import com.vk.liyj.service.UserInfoService;

    private String userNo;

    request.setAttribute("userList", userList);

    参照他事他说加以考查资料

    @Controller

    return updateTime;

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

    UserInfoService service;

    <dependency>

    } else {

    3、编写swagger注解

    }

    .description(

    1、在pom.xml中援花费swagger信任包

    本文由1010cc时时彩经典版发布于1010cc时时彩经典版,转载请注明出处:1010cc时时彩经典版SpringBoot学习笔记之集成swagge

    关键词: