1.添加Swagger UI依赖

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-swagger2</artifactId>
  4. <version>2.9.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.springfox</groupId>
  8. <artifactId>springfox-swagger-ui</artifactId>
  9. <version>2.9.2</version>
  10. </dependency>

2.创建配置文件SwaggerConfig

首先,在启动文件同级目录下创建一个config文件夹用以配置项目相关信息。在该文件夹下创建一个SwaggerConfig.java文件用以配置Swagger UI的相关信息,同时将Swagger注册为Bean,以使其注解有效。其代码如下:

  1. // SwaggerConfig.java
  2. @Configuration
  3. @EnableSwagger2
  4. public class SwaggerConfig {
  5. @Bean
  6. public Docket createRestApi() {
  7. return new Docket(DocumentationType.SWAGGER_2)
  8. .apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any())
  9. .paths(PathSelectors.any()).build();
  10. }
  11. private ApiInfo apiInfo() {
  12. return new ApiInfoBuilder()
  13. .title("Swagger Title") // 配置项目的Swagger UI标题
  14. .description("Swagger Description") // 配置描述信息
  15. .version("1.0.0-SNAPSHOT") // 项目版本信息
  16. .build();
  17. }
  18. }

3.给Controller添加注解

IndexController为例,给代码添加注解如下:

  1. @Api(value = "index测试类", description = "描述信息")
  2. @RestController
  3. @RequestMapping("/index")
  4. public class IndexController {
  5. @ApiOperation(value = "index", notes = "home测试方法") // tags
  6. @RequestMapping(value = "/home", method = RequestMethod.GET)
  7. public String index() {
  8. return "Hello,World";
  9. }
  10. }

访问默认路径http://localhost:8080/swagger-ui.html ,深入使用可查看官方文档:https://swagger.io/docs/

查看源码