springBoot大家都了解,那么就来介绍一下Swagger:
Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总 体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到 服务器端的代码,允许API来始终保持同步。
Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:
- Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API。
- Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
- Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
- Swagger 有一个强大的社区,里面有许多强悍的贡献者。
-
Swagger 文档提供了一个方法,使我们可以用指定的 JSON 或者 YAML 摘要来描述你的 API,包括了比如 names、order 等 API 信息。
你可以通过一个文本编辑器来编辑 Swagger 文件,或者你也可以从你的代码注释中自动生成。各种工具都可以使用 Swagger 文件来生成互动的 API 文档。
下面我们来看一下他和SpringBoot怎么结合使用:
首先创建springboot的maven项目之后添加依赖:
<!--依赖管理父节点的配置,简化maven的依赖管理-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--配置启动依赖和其他依赖-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--swagger2 依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<!--配置maven插件:可以用maven的形式启动Spring Boot项⽬(另外也可以在主方法中启动)--> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
再来看看 springBoot的配置文件:application.properties
#修改tomcat启动端⼝号
server.port=8088
#修改项⽬的部署路径
#server.servlet.context-path=/book
server.context-path=/book
#修改日志级别
logging.level.root=ERROR
#mysql配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.url=jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8
#jpa配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
之后我们来创建 swagger2的配置类
package com.itqf;
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.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;
/** * Created by liliting on 18/3/14. */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket getDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.select()
//.paths(Predicates.or(PathSelectors.regex("/api2/.*")))
// 过滤该路径下的请求生成RESTful api
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("BookStore Platform API")//大标题
.description("BookStore Platform's REST API, all the applications could access the Object model data via JSON.")//详细描述
.version("2.0")//版本
.contact(new Contact("java", "http://itqf.com", "123456@qq.com"))//作者
.license("The Apache License, Version 2.0")//许可证信息
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")//许可证地址
.build();
}
}
之后 开始创建pojo:
package com.itqf.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String author;
private double price;
private Date publishDate;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public Date getPublishDate() { return publishDate; }
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
}
dao层
package com.ww.dao.impl;
import com.ww.pojo.Book;
import org.springframework.data.jpa.repository.JpaRepository;
/** * Created by Sulliven on 19/2/27. */
public interface BookDaoImpl extends JpaRepository<Book,Integer> {
}
service层
接口:
package com.ww.service;
import com.ww.pojo.Book;
import java.util.List;
import java.util.Optional;
/** * Created by Sulliven on 19/2/27. */
public interface BookService {
public List<Book> findAll();
public Book findById(int id);
public void saveBook(Book book);
public void update(Book book);
public void delete(int id);
}
实现类:
package com.ww.service.impl;
import com.ww.dao.impl.BookDaoImpl;
import com.ww.pojo.Book;
import com.ww.service.BookService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List; import java.util.Optional;
@Service
public class BookServiceImpl implements BookService {
@Resource
private BookDaoImpl bookDaoImpl;
@Override
public List<Book> findAll() {
return bookDaoImpl.findAll();
}
@Override
public Book findById(int id) {
return bookDaoImpl.findOne(id);
}
@Override
public void saveBook(Book book) {
bookDaoImpl.save(book);
}
@Override
public void update(Book book) {
bookDaoImpl.saveAndFlush(book);
}
@Override
public void delete(int id) {
bookDaoImpl.delete(id);
}
}
最后是controller:
package com.ww.controller;
import com.ww.pojo.Book;
import com.ww.service.BookService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController //Controller+ResponseBody
@RequestMapping("/api1")
public class BookController {
@Resource
private BookService bookService;
@RequestMapping("/findAll")
public List<Book> findAll() {
System.out.print(111);
return bookService.findAll();
}
@PostMapping("/saveBook")
public Book save( @RequestBody Book book){ //json --》 对象
bookService.saveBook(book);
System.out.println(book);
return book;
}
@PutMapping("/updateBook")
public Book update(Book book){
bookService.update(book);
return book;
}
@DeleteMapping("/deleteBook")
public Map delete(int id){
Map map = new HashMap();
try{
bookService.delete(id);
map.put("result","success");
}catch (Exception e){
map.put("result","fail");
}
return map;
}
}
启动类:
package com.itqf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//位置:@SpringBootApplication
//1,main方法上 (常用)
//2,放到controller的类上 必须添加扫描其他包下的注解的代码 如: @ComponentScan("")
//SpringApplication.run 方法传的第一个参数的字节码对象就是Controller的class对象
public class SpringbootzhjpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootzhjpaApplication.class, args);
}
}
最后 执⾏行启动类 访问swagger2主页 :http://localhost:8088/book/swagger-ui.html 以下是效果图
还可以添加swagger文档注解
swagger默认生成的api文档都是英文的,可添加swagger文档注解,使api可得更通俗易懂。
常⽤用注解:
@Api()⽤用于类;
表示标识这个类是swagger的资源
@ApiOperation()用于方法;
表示一个http请求的操作
@ApiParam()⽤于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
@ApiModel()用于类 表示对类进行说明,用于参数用实体类接收
@ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
@ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
@ApiImplicitParam() 用于方法 表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
如在之前编写的controller中和pojo中的添加注解
pojo:
@Entity
@ApiModel(value = "图书对象",description = "对应图书表")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty(name="id",example = "1")
private int id;
@ApiModelProperty(name="name",example = "天⻰龙⼋八部")
private String name;
@ApiModelProperty(name="author",example = "⾦金金庸")
private String author;
@ApiModelProperty(name="price",example = "250.0")
private double price;
@ApiModelProperty(name="publishDate",example = "2019-02-27")
private Date publishDate;
//其余的与之前的pojo都一样
controller:
@RestController //Controller+ResponseBody
@RequestMapping("/api1")
@Api(description = "图书管理api",value = "管理图书")
public class BookController {
@Resource
private BookService bookService;
@ApiOperation(value = "查询所有图书")
@GetMapping("/findAll")
public List<Book> findAll() {
return bookService.findAll();
}
@ApiOperation(value = "新增图书")
@PostMapping("/saveBook")
public Book save(@ApiParam(value = "图书对象") @RequestBody Book book){
//json --》 对象
bookService.saveBook(book);
return book;
}
@ApiOperation(value = "修改图书",response = Book.class)
@PutMapping("/updateBook")
public Book update(@ApiParam(value = "图书对象") Book book){
bookService.update(book);
return book;
}
@ApiOperation(value = "删除图书")
@DeleteMapping("/deleteBook")
public Map delete(@ApiParam(required = true,value ="图书编号") int id){
Map map = new HashMap();
try{
bookService.delete(id);
map.put("result","success");
}catch (Exception e){
map.put("result","fail");
}
return map;
}
}
添加swagger⽂文档注释后效果 就有了中文的描述
以上就是与swegger得结合使用 并做了以下swgger的扩展