springboot2.0 + swagger配置

本文详细介绍了如何在SpringBoot项目中集成Swagger2和swagger-bootstrap-ui,包括配置pom依赖、Swagger配置类、静态资源过滤及注解使用,帮助开发者快速搭建API文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、配置过程

1、引入pom依赖

<dependency>
     <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
</dependency>

<!-- swagger-bootstrap-ui是基于swagger接口api实现的一套UI,因swagger原生ui是上下结构的,在浏览接口时不是很清晰,所以,swagger-bootstrap-ui是基于左右菜单风格的方式,适用与我们在开发后台系统左右结构这种风格类似,方便与接口浏览 -->
<dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>1.9.1</version>
</dependency>

2、配置swagger

@EnableSwagger2
@Configuration
public class Swagger2Configuration{
	@Bean
    	public Docket createRestApi() {
        		return new Docket(DocumentationType.SWAGGER_2)
                		.apiInfo(apiInfo())
                		.select()
                		.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//这是注意的代码
              		  //.apis(RequestHandlerSelectors.basePackage("com.skn.keelin")) 
              		  //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
               		 .paths(PathSelectors.any())
              		  //.paths(PathSelectors.regex("/.*"))
               		 .build();
    }

	private ApiInfo apiInfo() {
       		 return new ApiInfoBuilder()
              		  .title("xxx接口文档")
              		  .description("xxx相关接口的文档")
                		 .termsOfServiceUrl("http://www.xxx.com")
                		.version("1.0")
                		.build();
    }
}

3、配置swagger静态文件过滤

不进行此步骤,会报404

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    // 解决 swagger-ui.html 404报错
    registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    // 解决 doc.html 404 报错
    registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
}

4、swagger相关注解

参考:https://www.jb51.net/article/161877.htm

PS:WebMvcConfigurer接口

SpringBoot 2.0 后,靠实现WebMvcConfigurer接口来实现自己定义的一些Handler,Interceptor,ViewResolver,MessageConverter等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值