素材巴巴 > 程序开发 >

Swagger集成Springboot

程序开发 2023-09-13 20:26:06

Swagger集成Springboot

  • 2.Swagger使用
  • 3.访问
  • 1.Swagger介绍

    1.1.什么是Swagger

    Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

    Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。

    1.2.优势

    支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
    提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

    2.Swagger使用

    2.1.在pom.xml文件中添加第三方swagger依赖

            io.springfoxspringfox-swagger22.9.2io.springfoxspringfox-swagger-ui2.9.2
     

    2.1.2项目完整pom

    UTF-8UTF-81.81.3.22.0.25.1.321.1.10org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-jdbcorg.mybatis.spring.bootmybatis-spring-boot-starter${mybatis.starter.version}tk.mybatismapper-spring-boot-starter${mapper.starter.version}mysqlmysql-connector-java${mysql.version}com.alibabadruid-spring-boot-starter${durid.starter.version}io.springfoxspringfox-swagger22.9.2io.springfoxspringfox-swagger-ui2.9.2
     

    2.2.yml配置

    #Tomcat
     server:port: 9090
     #DB configuration
     spring:application:name: web-servicedatasource:url: jdbc:mysql://localhost:3306/work?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghaiusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver
     

    2.3.在Spring Boot项目的启动类上添加@EnableSwagger2,启动Swagger

    import org.springframework.boot.SpringApplication;
     import org.springframework.boot.autoconfigure.SpringBootApplication;
     import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
     import springfox.documentation.swagger2.annotations.EnableSwagger2;@SpringBootApplication
     @EnableSwagger2
     public class OneweekApplication {public static void main(String[] args) {SpringApplication.run(OneweekApplication.class, args);}}
     

    2.4.添加配置类

    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.spi.DocumentationType;
     import springfox.documentation.spring.web.plugins.Docket;
     import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
     @EnableSwagger2
     public class Swagger2Config {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().//自己的controller路径apis(RequestHandlerSelectors.basePackage("com.capgemini.controller")). paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("springboot利用swagger构建api文档").description("用户的CRUD").version("1.0").build();}
     }
     

    2.5.User实体类

    package com.capgemini.domain;import com.fasterxml.jackson.annotation.JsonFormat;
     import org.springframework.format.annotation.DateTimeFormat;import java.util.Date;
     import javax.persistence.*;@Table(name = "`user`")
     public class User {@Id@Column(name = "id")@GeneratedValue(generator = "JDBC")private Integer id;@Column(name = "username")private String username;@Column(name = "age")private Integer age;@Column(name = "sex")private String sex;@Column(name = "birthday")@DateTimeFormat(pattern = "yyyy-MM-dd")@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")private Date birthday;@Column(name = "phone")private String phone;@Transientprivate String sencode;@Transientprivate String code;public String getSencode() {return sencode;}public void setSencode(String sencode) {this.sencode = sencode;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}/*** @return id*/public Integer getId() {return id;}/*** @param id*/public void setId(Integer id) {this.id = id;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}/*** @return username*/public String getUsername() {return username;}/*** @param username*/public void setUsername(String username) {this.username = username;}/*** @return age*/public Integer getAge() {return age;}/*** @param age*/public void setAge(Integer age) {this.age = age;}/*** @return sex*/public String getSex() {return sex;}/*** @param sex*/public void setSex(String sex) {this.sex = sex;}/*** @return birthday*/public Date getBirthday() {return birthday;}/*** @param birthday*/public void setBirthday(Date birthday) {this.birthday = birthday;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append(getClass().getSimpleName());sb.append(" [");sb.append("Hash = ").append(hashCode());sb.append(", id=").append(id);sb.append(", username=").append(username);sb.append(", age=").append(age);sb.append(", sex=").append(sex);sb.append(", birthday=").append(birthday);sb.append(", phone=").append(phone);sb.append(", sencode=").append(sencode);sb.append(", code=").append(code);sb.append("]");return sb.toString();}
     }
     

    2.6.Mapper类(使用的通用mapper)

    package com.capgemini.dao;import com.capgemini.domain.User;
     import tk.mybatis.mapper.common.Mapper;@org.apache.ibatis.annotations.Mapper
     public interface UserMapper extends Mapper {
     }
     

    2.7.Service类

    package com.capgemini.service;
     import com.capgemini.domain.User;public interface UserService {//添加数据void addUser(User user);}

    2.8.Service实现类

    package com.capgemini.service.impl;import com.capgemini.domain.User;
     import org.springframework.stereotype.Service;import javax.annotation.Resource;import com.capgemini.dao.UserMapper;
     import com.capgemini.service.UserService;
     import org.springframework.transaction.annotation.Transactional;@Service
     @Transactional
     public class UserServiceImpl implements UserService {@Resourceprivate UserMapper userMapper;//添加用户@Overridepublic void addUser(User user) {userMapper.insert(user);}}
     

    2.9.Controller类

    package com.capgemini.controller;import com.capgemini.domain.MyException;
     import com.capgemini.domain.User;
     import com.capgemini.service.UserService;
     import com.capgemini.util.CommonUtil;
     import com.capgemini.vo.BaseResult;
     import io.swagger.annotations.ApiImplicitParam;
     import io.swagger.annotations.ApiOperation;
     import org.springframework.http.HttpStatus;
     import org.springframework.http.ResponseEntity;
     import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;//@Api 描述类  接口的主要用途
     //@ApiOperation  描述方法用途
     //@ApiImplicitParam  描述方法的参数
     //@ApiImplicitParams  描述方法的参数(Multi-Params)
     //@ApiIgnore 忽略某类/方法/参数的文档@RestController
     @RequestMapping("/user")
     public class UserController {@Resourceprivate UserService userService;//添加用户@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")@PostMappingpublic ResponseEntity addUser(@RequestBody User user) {BaseResult br = null;try {userService.addUser(user);br = new BaseResult(CommonUtil.SUCCESS, "添加成功");} catch (Exception e) {br = new BaseResult(CommonUtil.FAIL, "添加失败");}return new ResponseEntity<>(br, HttpStatus.OK);}
     }
     

    3.访问

    http://localhost:9090/swagger-ui.html#/
    在这里插入图片描述


    标签:

    上一篇: AngularJs学习(1)[控制器,过滤器] 下一篇:
    素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。