springboot配置swagger2

swagger2作用

在项目中,后端开发的接口通常需要自测之后,再去和前端同事联调,以节省时间,提高效率,而自测一般有以下几种方法:

  • 手写junit单元测试
  • 使用google浏览器插件postman测试
  • 项目中配置swagger2

这篇文章主要介绍springboot项目中配置swagger2的步骤

swagger配置

1.pom依赖

本文选择配置2.5.0的swagger,喜欢用更新版本的也可以自行选择,配置方式基本一样。

	<dependency>
				<groupId>io.springfox</groupId>
				<artifactId>springfox-swagger2</artifactId>
				<version>2.5.0</version>
	</dependency>
	<dependency>
				<groupId>io.springfox</groupId>
				<artifactId>springfox-swagger-ui</artifactId>
				<version>2.5.0</version>
	</dependency>

2.swagger配置类

配置的时候有几个点需要注意

  • @EnableSwagger2注解,自动开启swagger2,这个注解也可以在这里不写,加在启动主类上也行。
  • @ComponentScan(“xxx”)这里写入需要扫描的接口的包位置,可以写多个
  • genericModelSubstitutes(DeferredResult.class)这个方法不要少,不然有可能会无法生成json参数模板
  • 用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean;喜欢用xml的可以自行替换。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;

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
@ComponentScan({"com.myproject.demo.controller"})
public class Swagger2 {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
				.genericModelSubstitutes(DeferredResult.class)
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.myproject.demo.controller"))
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		ApiInfo apiInfo = new ApiInfoBuilder().title("SpringBoot-swagger ui")
				.description("SpringBoot-swagger ui")
				.license("MIT")
				.licenseUrl("http://opensource.org/licenses/MIT")
				.version("1.0")
				.build();
		return apiInfo;
	}

}

配置好以上步骤之后,就可以访问swagger界面了,启动服务,输入访问地址http://localhost:8080/demo/swagger-ui.html即可成功访问。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值