1 编写SpringBoot项目
新建一个Rest请求控制器。
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@PostMapping("/post")
public String post(){
return "post";
}
@GetMapping("/get")
public String get(String a,String b){
return "get";
}
@RequestMapping("/req")
public String req(String m){
return "req";
}
}
2 导入Spring-fox依赖
在项目的pom.xml中导入Spring-fox依赖。目前最新版本为2.9.2,所以导入的依赖也是这个版本。其中springfox-swagger2是核心内容的封装。springfox-swagger-ui是对swagger-ui的封装。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>swaggerDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
</project>
3 添加注解
在SpringBoot的启动类中添加@EnableSwagger2注解。
添加此注解后表示对当前项目中全部控制器进行扫描。应用Swagger2
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class);
}
}
4 访问swagger-ui
启动项目后在浏览器中输入http://ip:8080/swagger-ui.html即可以访问到swagger-ui页面,在页面中可以可视化的进行操作项目中所有接口。