SpringBoot集成Swagger(Springfox)自动生成API文档

也许,你事先需要了解Swagger和Springfox的关系,然后我默认大家都在使用SpringBoot,并且对Java和Spring有一定的开发基础。

万物皆麻烦,直接上代码(博文末尾有github源码地址)

1.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>

	<!-- 2.0.3版本的spring-boot-starter-parent -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/>
	</parent>

	<!-- 项目相关 -->
	<groupId>com.zaomianbao</groupId>
	<artifactId>swagger</artifactId>
	<version>1.0.0</version>
	<name>swagger</name>
	<description>Demo project for Swagger</description>

	<!-- java版本 -->
	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!-- SpringBoot相关依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- lombok敏捷开发工具包-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<!-- google guava util-->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>27.0.1-jre</version>
		</dependency>

		<!-- springfox -->
		<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>

		<!-- json -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.6.5</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.6</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.9.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.7</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
	</dependencies>

	<!-- SpringBoot的maven插件 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

这里面最重要的是springfox的两个配置

<!-- swagger核心组件,在代码配置swagger时会依赖到它 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<!-- swagger的用户界面,用于展示api接口文档 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

2.Swagger配置类

package com.zaomianbao.swagger.config;

import com.google.common.base.Predicate;
import com.zaomianbao.swagger.annotation.SwaggerCustomIgnore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;
import static com.google.common.base.Predicates.*;
import static springfox.documentation.builders.RequestHandlerSelectors.*;
import static springfox.documentation.builders.PathSelectors.*;

/**
 * @Description Swagger配置文件
 * @Author zaomianbao
 * @Date 2019/1/9
 **/
//该类依赖了google的guava组件和springfox.documentation组件
@Configuration
@EnableSwagger2
//包扫描,在此包下的Controler都会被纳入swagger接口文档生成的范围,这里也可以配置类扫描,同时也可以在这个配置类里面细化过滤规则
@ComponentScan(basePackages = "com.zaomianbao.swagger.controller")
public class SpringfoxSwagger2Config {

    //组织Docket对象,翻译过来就是摘要的意思,它是生成API文档的核心对象,里面配置一些必要的信息
    @Bean
    public Docket swaggerSpringMvcPlugin(){
                        //指定规范,这里是SWAGGER_2
        return new Docket(DocumentationType.SWAGGER_2)
                //设定Api文档头信息,这个信息会展示在文档UI的头部位置
                .apiInfo(swaggerDemoApiInfo())
                .select()
                //添加过滤条件,谓词过滤predicate,这里是自定义注解进行过滤
                .apis(not(withMethodAnnotation(SwaggerCustomIgnore.class)))
                //这里配合@ComponentScan一起使用,又再次细化了匹配规则(当然,我们也可以只选择@ComponentScan、paths()方法当中的一中)
                .paths(allowPaths())
                .build();
    }

    /**
     * 自定义API文档基本信息实体
     * @return
     */
    private ApiInfo swaggerDemoApiInfo(){
        //构建联系实体,在UI界面会显示
        Contact contact = new Contact("枣面包", "http://www.zaomianbao.com", "zaomianbao@163.com");
        return new ApiInfoBuilder()
                    .contact(contact)
                    //文档标题
                    .title("Swagger2构建RESTful API文档")
                    //文档描述
                    .description("SpringBoot集成Springbox开源项目,实现OAS,构建成RESTful API文档")
                    //文档版本
                    .version("1.0.0")
                    .build();
    }

    /**
     * path匹配规则
     * @return
     */
    private Predicate<String> allowPaths(){
        return or(
                regex("/user.*"),
                regex("/role.*")
        );
    }
}

配置是自定义的,有些配置可以没有,有些配置可以再加上,多余配置可以参考官方文档:Springfox Reference Documentation

3.忽略接口注解SwaggerCustomIgnore

这个注解在Swagger配置类中和下面的范例UserController中使用到了,哪个方法被该注解标注了,那么对应方法的接口就会被API文档忽略构建

package com.zaomianbao.swagger.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 忽略接口注解
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SwaggerCustomIgnore {
}

4.范例UserController

这里提供了一些范例接口,供生成API文档

package com.zaomianbao.swagger.controller;

import com.zaomianbao.swagger.annotation.SwaggerCustomIgnore;
import com.zaomianbao.swagger.entity.User;
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;
import java.util.Arrays;

/**
 * @Description 用户控制层
 * @Author zaomianbao
 * @Date 2019/1/9
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @SwaggerCustomIgnore
    @GetMapping("/list")
    public Object getUserList(){
        return Arrays.asList(User.builder().age(18).username("枣面包").build());
    }

    @PostMapping("create")
    public Object creteUser(){
        return User.builder().age(18).username("枣面包").build();
    }
}

5.使用到的实体User

使用到的实体,这里使用的lombok组件,在pom中已经引入

package com.zaomianbao.swagger.entity;

import lombok.Builder;
import lombok.Data;

/**
 * @Description 用户实体
 * @Author zaomianbao
 * @Date 2019/1/9
 **/
@Data
@Builder
public class User {

    private String username;
    private Integer age;
}

6.项目包结构

在这里插入图片描述

7.Swagger-UI

启动项目直接访问:http://localhost:8080/swagger-ui.html
在这里插入图片描述
UI和配置的对应关系

1.对应配置里的title
2.对应配置里的version
3.对应配置里的description
4.对应配置里的Contact对象
5.对应配置里的@ComponentScan注解、paths()方法、allowPaths()方法、UserControler里@SwaggerCustomIgnore注解共同作用下展示出来的结果

在swagger-ui里我们还可以模拟请求,直接测试接口的功能

点击每个接口对应的显示区域 --> 点击"try it out" --> 点击"execute"即可
在这里插入图片描述

8.注意

在我们的接口所在的Controller里其实可以配置很多注解用于描述和丰富API文档,但是博主这里并没有使用,当然,没有配置那么多注解也一样可以使用,一样可以生成API文档,只是那些注解会丰富生成的JSON格式的API文档文件(这个可以在博主之前的博客中找到原因:Swagger和Springfox的关系),然后通过swagger-ui展示给大家而已。这里只是一个入门,和扫盲的过程。

9.github源码地址

https://github.com/zaomianbao/swagger

10.总结

如有错误,请在留言板给博主留言,博主会第一时间更正。

参考:

https://swagger.io/
http://springfox.github.io/springfox/docs/snapshot/
http://www.cnblogs.com/getupmorning/p/7267076.html
http://springfox.github.io/springfox/
https://petstore.swagger.io/
https://editor.swagger.io/
https://www.jianshu.com/p/cdb41c9e52e2
https://github.com/swagger-api
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring Boot集成Swagger是为了更方便地生成API文档,使得API文档更加规范、易读和易于维护。 Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。Spring Boot是一个快速开发框架,集成了大量的开箱即用的功能,能够帮助开发者快速地构建应用。 在Spring Boot中集成Swagger,需要引入相应的依赖,配置Swagger相关的注解和配置信息。通过访问Swagger UI页面,可以方便地查看API文档、测试API接口等。 通过Spring Boot集成Swagger,我们可以更好地管理和维护API文档,提高开发效率和代码质量。 ### 回答2: Spring Boot可以通过集成Swagger自动生成API文档Swagger是一个规范和工具集,用于设计、构建和维护RESTful风格的API文档。以下是集成Swagger的步骤: 1. 在pom.xml文件中添加Swagger依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.3.1</version> </dependency> ``` 2. 创建一个Swagger配置类,使用@EnableSwagger2注解启用Swagger: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } } ``` 3. 使用Swagger注解描述API接口。在Controller类或方法上添加@Api、@ApiOperation等注解来描述API的信息、请求和响应参数等。 4. 运行Spring Boot应用程序,并访问"http://localhost:8080/swagger-ui.html",可以看到自动生成API文档页面。 集成Swagger可以方便地为API接口生成文档,并且可以在页面上进行测试。开发人员和客户端可以根据这些文档了解API的使用方式和参数要求,减少沟通成本,提高开发效率。 ### 回答3: Spring Boot是用于构建Java应用程序的开源框架,而Swagger是用于设计、构建和文档化RESTful API的工具。将Swagger集成到Spring Boot项目中,可以方便地生成API文档,并提供交互式API文档浏览界面。 首先,需要在项目的pom.xml文件中添加Swagger依赖。可以使用以下代码片段添加Swagger的依赖: ```xml <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> ``` 添加完依赖之后,需要创建一个配置类来启用Swagger。可以创建一个名为SwaggerConfig的类,并使用@EnableSwagger2注解启用Swagger。 ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } } ``` 在这个配置类中,可以通过api()方法来配置Swagger的一些参数,例如扫描的包路径、API路径等。 配置完成后,可以通过访问http://localhost:8080/swagger-ui.html来查看Swagger生成的API文档。在这个界面上,可以查看每个API的详细信息,包括请求参数、响应类型等。同时,还提供了测试API的功能,方便进行接口的调试和测试。 需要注意的是,集成Swagger只是在项目中添加了API文档的功能,实际的API实现还需要编写具体的业务逻辑代码。 综上所述,通过上述步骤,我们可以将Swagger集成到Spring Boot项目中,并生成具有交互性的API文档界面,方便开发和测试人员查阅和测试API接口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值