springboot+swagger前后端分离的利器

 

        前后端分离后,维护接口文档基本上是必不可少的工作。一个理想的状态是设计好后,接口文档发给前端和后端,大伙按照既定的规则各自开发,开发好了对接上了就可以上线了。当然这是一种非常理想的状态,实际开发中却很少遇到这样的情况,接口总是在不断的变化之中,有变化就要去维护,本文主要和大伙来聊下在Spring Boot中如何整合Swagger2。

 

注解及其说明

@Api : 用在类上,说明该类的主要作用。

@ApiOperation:用在方法上,给API增加方法说明。

@ApiImplicitParams : 用在方法上,包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。

 

1.配置需要的pom.xml文件


    <dependencies>
        <dependency> <!--添加Web依赖 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency><!--添加Swagger依赖 -->
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency><!--添加Swagger-UI依赖 -->
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency> <!--添加热部署依赖 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency><!--添加Test依赖 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.添加swagger2配置

package com.zhou.swagger2.config;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .apis(RequestHandlerSelectors.basePackage("com.zhou"))
                .build();
    }
    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("网站-中心API文档")
                .description("本文档描述了接口定义")
                .version("1.0")
                .contact(new Contact("hello", "https://blog.csdn.net/u013010499",
                        "6666666666@qq.com"))
                .build();
    }


}

/**
 * @program: jpademo
 * @description: Employee
 * @author: ZengGuangfu
 * @create 2018-10-23 10:20
 */
​
@Data
@ApiModel(value = "用户对象模型")
public class Employee {
​
   private Integer employeeId;
​
   @ApiModelProperty(value = "用户名",required = true)
   private String userName;
​
   @ApiModelProperty(value = "年龄",required = true)
   private Integer age;
​
   @ApiModelProperty(value = "年级",required = true)
   private Integer graId;
​
   public interface Audit{};
​
   public interface Children{};
​
}

3创建测试接口


/**
 * @program: jpademo
 * @description: EmployeeController
 * @author: ZengGuangfu
 * @create 2018-10-23 11:07
 */
​
@RestController
@RequestMapping("emp")
@Api(value = "用户管理类")
public class EmployeeController {
​
 @Autowired
 private EmployeeReposiroty employeeReposiroty;
​
      /**
      * 增加人物
      * @param employee
      * @return
      */
     @PostMapping(value = "employee")
     @ApiOperation(value = "新增一个用户",notes = "新增之后返回对象")
     @ApiImplicitParam(paramType = "query",name = "employee",value = "用户",required = true)
     @ApiResponse(code = 400,message = "参数没有填好",response = String.class)
     public String insert(Employee employee){
         Employee employee1 = employeeReposiroty.save(employee);
         if(employee1 != null) {
             return SysNode.Judge.SUCCESS.getResult();
         }else {
             return SysNode.Judge.FAILD.getResult();
         }
     }
​
      /**
      * 删除单个用户
      * @param id
      * @return
      */
      @DeleteMapping(value = "employee/{id}")
      @ApiOperation(value = "删除用户",notes = "根据成员id删除单个用户")
      @ApiImplicitParam(paramType = "path",name = "id",value = "用户id",required = true,dataType = "Integer")
      @ApiResponse(code = 400,message = "参数没有填好",response = String.class)
      public String delete(@PathVariable("id")Integer id){
           try{
                employeeReposiroty.deleteById(id);
                return SysNode.Judge.SUCCESS.getResult();
           }catch (Exception e){
                e.printStackTrace();
               return SysNode.Judge.FAILD.getResult();
           }
      }
​
      /**
      * 修改单个成员
      * @param employee
      * @return
      */
      @PutMapping(value = "employee/{id}")
      @ApiOperation(value = "修改用户信息",notes = "根据成员id修改单个用户")
      public String update(Employee employee){
           /**
           * save方法如果参数属性缺失,会导致原本存在的数据为null
           */
           Employee employee1 = employeeReposiroty.saveAndFlush(employee);
           if (employee1 != null) {
                return SysNode.Judge.SUCCESS.getResult();
           }else {
               return SysNode.Judge.FAILD.getResult();
           }
      }
​
      /**
      * 获取所有成员,升序排列
      * @return
      */
      @GetMapping(value = "employee/sort")
      @ApiOperation(value = "查询全部用户",notes = "默认根据升序查询全部用户信息")
      public List<Employee> findAll(){
           Sort orders = new Sort(Sort.Direction.DESC,"employeeId");
           List<Employee> employeeList = employeeReposiroty.findAll(orders);
           return employeeList;
      }
​
      /**
     * 获取所有成员,升序排列
     * @return
      */
      @GetMapping(value = "employee/pageSort")
      @ApiOperation(value = "查询用户信息",notes = "查询用户信息")
      @ApiImplicitParams({
           @ApiImplicitParam(paramType = "query",name = "sort",value = "排序方式:asc|desc",dataType = "String",required = true),
           @ApiImplicitParam(paramType = "query",name = "pagenumber",value = "第几页",dataType = "Integer",required = true),
           @ApiImplicitParam(paramType = "query",name = "pageSize",value = "分页数",dataType = "Integer",required = true)
      })
      public List<Employee> findAllByPage(String sort,Integer pagenumber,Integer pageSize){
           try {
                Sort.Direction sortlast;
                if("desc".equals(sort.toLowerCase())){
                     sortlast = Sort.Direction.DESC;
               }else{          
                      sortlast = Sort.Direction.ASC;
               }
                     Sort orders = new Sort(sortlast, "employeeId");
                     Pageable pageable = new PageRequest(pagenumber, pageSize, orders);
​
                     Page<Employee> employeePage = employeeReposiroty.findAll(pageable);
                     List<Employee> employeeList = employeePage.getContent();
                     return employeeList;
           }catch (Exception e){
                e.printStackTrace();
                return null;
           }
      }
    /**
     * 自定义拓展jpa,根据用户名查找单个用户
     * @param username
     * @return
     */
     @GetMapping(value = "employee/find/{username}")
     @ApiOperation(value = "查询用户信息",notes = "根据用户登录名查询该用户信息")
     @ApiImplicitParam(paramType = "path",name = "username",value = "用户登录名",required = true,dataType = "String")
     public Employee findByUsername(@PathVariable("username") String username){
         List<Employee> employeeList = employeeReposiroty.findByUserNameOrderByEmployeeIdAsc(username);
         if (employeeList != null && !employeeList.isEmpty()){
             return employeeList.get(0);
         }
         return null;
     }
​
     /**
     * 测试用
     * @return
     */
     @GetMapping(value = "employee/grade")
     public List<Object[]> findEmployeeAndGrade(){
         Pageable pageable = new PageRequest(0,3);
​
         Page<Object[]> page = employeeReposiroty.findEmployeeAndGrade(pageable);
         System.out.println(page.getTotalElements()+"----------结果总数------------");
         System.out.println(page.getTotalPages()+"--------根据pageSize的总页数-----------");
         System.out.println(page.getNumber()+"--------当前页数,pageNumber----------");
         System.out.println(page.getNumberOfElements()+"--------当前页有几个数据--------");
         System.out.println(page.getSize()+"---------PageSize-------------");
         System.out.println(page.getSort()+"---------排序方式,没有则是'UNSORTED'----------");
​
         List<Object[]> objects = page.getContent();
         return objects;
    }
}

 

在这里插入图片描述

修改

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭优秀的笔记

你的支持就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值