栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot集成swagger过程解析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot集成swagger过程解析

这篇文章主要介绍了springboot集成swagger过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

springboot集成swagger

1、pom.xml中引入:


      io.springfox
      springfox-swagger2
      2.9.2
    
    
      io.springfox
      springfox-swagger-ui
      2.9.2
    

2、配置类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
  @Bean
  public Docket swaggerSpringMvcPlugin() {

    return new Docket(documentationType.SWAGGER_2)
 .select()
 //加了ApiOperation注解的类,才生成接口文档
 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
 .build();
  }

}

3、controller相应的注解:@ApiOperation

@ApiOperation(value = "用户登录",notes = "")
  @PostMapping("/loginOn")
  public ResponseMessage loginOn(@RequestBody @Valid UserReq userReq){
    ResponseMessage responseMessage = userServiceImp.loginOn(userReq);
    return responseMessage;
  }

最后本地默认访问:http://localhost:8080/swagger-ui.html

既可以看到相关接口效果图:

访问页失败的可能原因:

1》》访问方法本来就是404错误:在sprigboot中有个重要的概念叫做:约定优于配置:

springboot启动的时候如果没有指定扫描的包路径时,默认会去加载其当前包及子包下的组件,这里需要注意

如果把启动类放入service包下,页面就会访问不到:

2》》SwaggerConfig 类的写法有问题:Docket方法挺多的,这里需要注意:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
  @Bean
  public Docket swaggerSpringMvcPlugin() {

    return new Docket(documentationType.SWAGGER_2)
 .select()
 //加了ApiOperation注解的类,才生成接口文档
 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
 .build();
  }

}

3》》配置拦截器时是否进行了拦截:

在实现WebMvcConfigurer接口时,我们再配置拦截器时,需要对相应的请求进行过滤放行,比如静态资源,登录请求等

@Configuration
public class WebConfig implements WebMvcConfigurer {
  
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/*
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //过滤swagger
    registry.addResourceHandler("swagger-ui.html")
 .addResourceLocations("classpath:/meta-INF/resources/");

    registry.addResourceHandler("/webjars/**")
 .addResourceLocations("classpath:/meta-INF/resources/webjars/");

    registry.addResourceHandler("/swagger-resources/**")
 .addResourceLocations("classpath:/meta-INF/resources/swagger-resources/");

    registry.addResourceHandler("/swagger/**")
 .addResourceLocations("classpath:/meta-INF/resources/swagger*");

    registry.addResourceHandler("/v2/api-docs/**")
 .addResourceLocations("classpath:/meta-INF/resources/v2/api-docs/");

  }*

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号