1、新建一个SpringBoot web项目
2、导入Swagger依赖
ps:刚开始我用的3.0.0版本的springfox-swagger2和springfox-swagger-ui,但输入http://localhost:8080/swagger-ui.html之后swagger页面死活加载不出来,总是出现错误页面。后来换成了2.9.2版本之后,页面就可以加载出来了!
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
3、编写一个Hello工程
-
新建项目结构如下图所示:
-
新建HelloController.java:
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
-
运行SwaggerDemoApplication.java,浏览器输入localhost:8080/hello,出现以下页面说明程序运行成功!
4、配置Swagger
-
如下图所示,在swagger目录下新建配置目录config,在config下新建SwaggerConfig类,配置Swagger。
-
SwaggerConfig类内容如下:
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
5、测试运行
浏览器输入http://localhost:8080/swagger-ui.html,结果如下: