SpringBoot整合Swagger2


打开https://start.spring.io/

在线构建一个SpringBoot Maven项目

 点击Generate生成 下载压缩包

打开eclips  -> File ->Import   导入现有maven项目

打开pom.xml,加入web模块依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>

先添加一个测试controller看是否正常:

添加controller包,添加一个HelloControler.java 。

controller的包要在自动生成的Application.java的外面一层、 即和Application.java所在包为同级目录,否则会出现404

@RestController
public class HelloController {
     
    @GetMapping("/hello")
    public String hello(String name)      
    {
        return "Hello " +name;
    } 
    
    
}

右键项目 

Run as -Maven Install  等待安装结束

出现说明安装完

DemoApplication.java -> Run as -> Java Application

浏览器打开 http://localhost:8080/hello?name=test  输出正确说明配置成功

添加Swagger2依赖:

<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.9.2version>
dependency>
<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger-uiartifactId>
    <version>2.9.2version>
dependency>

添加SwaggerConfig类

package com.example.demo.config;
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 SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Kitty API Doc")
                .description("This is a restful api document of Kitty.")
                .version("1.0")
                .build();
    }
}

在刚才添加的控制器中加入注解:


package com.example.demo.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/*
类注解 */ @Api(value = "desc of class") @RestController public class HelloController { /* 方法注解 */ @ApiOperation(value = "desc of method", notes = "") @GetMapping("/hello") public String hello(/* 参数注解 */ @ApiParam(value = "desc of param" , required=true ) @RequestParam String name) { return "Hello"+name; }

浏览器打开 :  http://localhost:8080/swagger-ui.html#/