springboot集成swagger2

参考官方资料:http://springfox.github.io/springfox/docs/current/

https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#schema

其他:https://dzone.com/articles/spring-boot-2-restful-api-documentation-with-swagg

一、创建项目

1.创建一个简单的maven项目springboot-swagger2

2.pom文件依赖如下

<?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>com.zsx</groupId>
    <artifactId>springboot-swagger2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>11</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath />
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- swagger2所需依赖 -->
        <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>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、配置swagger2

创建配置类Swagger2Config.java

package com.zsx.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors
                        .basePackage("com.zsx.api.controller"))
                .paths(PathSelectors.regex("/.*"))
                .build().apiInfo(apiEndPointsInfo());
    }

    private ApiInfo apiEndPointsInfo() {
        return new ApiInfoBuilder().title("Spring Boot REST API")
                .description("User Management REST API")
                .contact(new Contact("zsx", "http://localhost:8080", "xxx@163.com"))
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .version("1.0.0")
                .build();
    }
}

三、创建用户实体类

package com.zsx.entity;

import java.io.Serializable;

public class User implements Serializable {

    private String id;
    private String name;
    private Integer age;

    public User() {
    }

    public User(String id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

四、 编写用户api接口

package com.zsx.api.controller;

import com.zsx.entity.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@RestController
@RequestMapping("/api/v1")
@EnableSwagger2
public class UserController {

    @ApiOperation(value = "根据id获取用户信息", notes = "id不能为空")
    @GetMapping("user/{id}")
    public User get(String id) {
        if ("123".equals(id)) {
            return new User("123", "zhangsan", 18);
        }
        return new User();
    }

    @PostMapping("user")
    public String insert(@RequestBody User user) {
        user.setId("1234");
        return user.getId();
    }

    @DeleteMapping("user/{id}")
    public String delete(@RequestBody User user) {
        user.setId("1234");
        return user.getId();
    }

    @PutMapping("user")
    public String update(@RequestBody User user) {
        user.setId("1234");
        return user.getId();
    }
}

五、创建引导类

package com.zsx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Swagger2Application {

    public static void main(String[] args) {
        SpringApplication.run(Swagger2Application.class, args);
    }
}

六、启动引导类

H:\JDK\jdk-11.0.3\bin\java.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=54368:H:\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\springboot\springbootswagger2\target\classes;E:\maven\repository\org\springframework\boot\spring-boot-starter-web\2.1.4.RELEASE\spring-boot-starter-web-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter\2.1.4.RELEASE\spring-boot-starter-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot\2.1.4.RELEASE\spring-boot-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.4.RELEASE\spring-boot-autoconfigure-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-logging\2.1.4.RELEASE\spring-boot-starter-logging-2.1.4.RELEASE.jar;E:\maven\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\maven\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\maven\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;E:\maven\repository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;E:\maven\repository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\maven\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;E:\maven\repository\org\springframework\spring-core\5.1.6.RELEASE\spring-core-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-jcl\5.1.6.RELEASE\spring-jcl-5.1.6.RELEASE.jar;E:\maven\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-json\2.1.4.RELEASE\spring-boot-starter-json-2.1.4.RELEASE.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.4.RELEASE\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.17\tomcat-embed-core-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.17\tomcat-embed-el-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.17\tomcat-embed-websocket-9.0.17.jar;E:\maven\repository\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;E:\maven\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;E:\maven\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;E:\maven\repository\org\springframework\spring-web\5.1.6.RELEASE\spring-web-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-beans\5.1.6.RELEASE\spring-beans-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-webmvc\5.1.6.RELEASE\spring-webmvc-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-aop\5.1.6.RELEASE\spring-aop-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-context\5.1.6.RELEASE\spring-context-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-expression\5.1.6.RELEASE\spring-expression-5.1.6.RELEASE.jar;E:\maven\repository\io\springfox\springfox-swagger2\2.9.2\springfox-swagger2-2.9.2.jar;E:\maven\repository\io\swagger\swagger-annotations\1.5.20\swagger-annotations-1.5.20.jar;E:\maven\repository\io\swagger\swagger-models\1.5.20\swagger-models-1.5.20.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;E:\maven\repository\io\springfox\springfox-spi\2.9.2\springfox-spi-2.9.2.jar;E:\maven\repository\io\springfox\springfox-core\2.9.2\springfox-core-2.9.2.jar;E:\maven\repository\net\bytebuddy\byte-buddy\1.9.12\byte-buddy-1.9.12.jar;E:\maven\repository\io\springfox\springfox-schema\2.9.2\springfox-schema-2.9.2.jar;E:\maven\repository\io\springfox\springfox-swagger-common\2.9.2\springfox-swagger-common-2.9.2.jar;E:\maven\repository\io\springfox\springfox-spring-web\2.9.2\springfox-spring-web-2.9.2.jar;E:\maven\repository\com\google\guava\guava\20.0\guava-20.0.jar;E:\maven\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;E:\maven\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\maven\repository\org\springframework\plugin\spring-plugin-core\1.2.0.RELEASE\spring-plugin-core-1.2.0.RELEASE.jar;E:\maven\repository\org\springframework\plugin\spring-plugin-metadata\1.2.0.RELEASE\spring-plugin-metadata-1.2.0.RELEASE.jar;E:\maven\repository\org\mapstruct\mapstruct\1.2.0.Final\mapstruct-1.2.0.Final.jar;E:\maven\repository\io\springfox\springfox-swagger-ui\2.9.2\springfox-swagger-ui-2.9.2.jar com.zsx.Swagger2Application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-07-07 00:47:06.121  INFO 7420 --- [           main] com.zsx.Swagger2Application              : Starting Swagger2Application on zsx with PID 7420 (F:\IdeaProjects\springboot\springbootswagger2\target\classes started by admin in F:\IdeaProjects\springbootmongodb)
2019-07-07 00:47:06.123  INFO 7420 --- [           main] com.zsx.Swagger2Application              : No active profile set, falling back to default profiles: default
2019-07-07 00:47:08.148  INFO 7420 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-07 00:47:08.182  INFO 7420 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-07 00:47:08.182  INFO 7420 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-07-07 00:47:08.190  INFO 7420 --- [           main] o.a.catalina.core.AprLifecycleListener   : An older version [1.2.16] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.21]
2019-07-07 00:47:08.191  INFO 7420 --- [           main] o.a.catalina.core.AprLifecycleListener   : Loaded APR based Apache Tomcat Native library [1.2.16] using APR version [1.6.3].
2019-07-07 00:47:08.191  INFO 7420 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-07-07 00:47:08.191  INFO 7420 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-07-07 00:47:09.256  INFO 7420 --- [           main] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.0.2m  2 Nov 2017]
2019-07-07 00:47:09.492  INFO 7420 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-07 00:47:09.492  INFO 7420 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3203 ms
2019-07-07 00:47:09.994  INFO 7420 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2019-07-07 00:47:10.197  INFO 7420 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-07 00:47:10.418  INFO 7420 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2019-07-07 00:47:10.446  INFO 7420 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2019-07-07 00:47:10.497  INFO 7420 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2019-07-07 00:47:10.706  INFO 7420 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-07 00:47:10.710  INFO 7420 --- [           main] com.zsx.Swagger2Application              : Started Swagger2Application in 5.64 seconds (JVM running for 7.909)

七、查看请求

1. 打开浏览器,查看请求http://localhost:8080/swagger-ui.html#/

到此集成swagger成功 

注:

swagger 2.0 @Api description description(暂未验证)
官方解决方案:https://github.com/swagger-api/swagger-core/issues/1476
stackoverflow解决方案:https://stackoverflow.com/questions/38074936/api-annotations-description-is-deprecated

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值