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 publicclassSwaggerConfig{ @Bean publicDocketswaggerSpringMvcPlugin(){ returnnewDocket(DocumentationType.SWAGGER_2) .select() //加了ApiOperation注解的类,才生成接口文档 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build(); } }
3、controller相应的注解:@ApiOperation
@ApiOperation(value="用户登录",notes="") @PostMapping("/loginOn") publicResponseMessageloginOn(@RequestBody@ValidUserRequserReq){ ResponseMessageresponseMessage=userServiceImp.loginOn(userReq); returnresponseMessage; }
最后本地默认访问:http://localhost:8080/swagger-ui.html
既可以看到相关接口效果图:
1》》访问方法本来就是404错误:在sprigboot中有个重要的概念叫做:约定优于配置:
springboot启动的时候如果没有指定扫描的包路径时,默认会去加载其当前包及子包下的组件,这里需要注意
@Configuration @EnableSwagger2 publicclassSwaggerConfig{ @Bean publicDocketswaggerSpringMvcPlugin(){ returnnewDocket(DocumentationType.SWAGGER_2) .select() //加了ApiOperation注解的类,才生成接口文档 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build(); } }
3》》配置拦截器时是否进行了拦截:
在实现WebMvcConfigurer接口时,我们再配置拦截器时,需要对相应的请求进行过滤放行,比如静态资源,登录请求等
@Configuration publicclassWebConfigimplementsWebMvcConfigurer{ /** *配置拦截器 *@paramregistry */ @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ registry.addInterceptor(newRequestInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login") //排除swagger .excludePathPatterns("/swagger-resources/**","/webjars/**", "/v2/**","/swagger-ui.html/**"); } }
有的代码是通过重写WebMvcConfigurer的addResourceHandlers方法:
/** *添加静态资源--过滤swagger-api(开源的在线API文档) *@paramregistry *//* @Override publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){ //过滤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/"); }*
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。