详解如何在SpringBoot里使用SwaggerUI
Swagger
Swagger是一种和语言无关的规范和框架,用于定义服务接口,主要用于描述RESTful的API。它专注于为API创建优秀的文档和客户端库。支持Swagger的API可以为API方法生成交互式的文档,让用户可以通过以可视化的方式试验,查看请求和响应、头文件和返回代码,从而发现API的功能。
swagger用于定义API文档。
好处:
- 前后端分离开发
- API文档非常明确
- 测试的时候不需要再使用URL输入浏览器的方式来访问Controller
- 传统的输入URL的测试方式对于post请求的传参比较麻烦(当然,可以使用postman这样的浏览器插件)
- spring-boot与swagger的集比较成简单
SpringBoot嵌入SwaggerUI
步骤
1.jar包引入
io.springfox springfox-swagger-ui 2.2.2 compile io.springfox springfox-swagger2 2.2.2 compile
2.基于SpringBoot配置SwaggerConfig
@Configuration @EnableSwagger2 publicclassSwaggerConfig{ @Bean publicDocketnewsApi(){ //returnnewDocket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().paths(PathSelectors.any()).build(); Docketdocket=newDocket(DocumentationType.SWAGGER_2); docket.enable(true); docket.apiInfo(apiInfo()).select().paths(PathSelectors.any()).build(); returndocket; } privateApiInfoapiInfo(){ returnnewApiInfoBuilder().title("订单中心测试平台").description("在这里你可以浏览项目所有接口,并提供相关测试工具") .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open").contact("test") .license("ChinaRedStarLicenceVersion1.0").licenseUrl("#").version("1.0").build(); } }
3.WebConfig配置说明
这里有一个需要注意的问题,让WebConfig去继承WebMvcAutoConfigurationAdapter而不是直接继承WebMvcConfigurerAdapter,否则Swagger的页面出不来。
@Configuration @EnableWebMvc publicclassWebConfigextendsWebMvcAutoConfigurationAdapter{ @Override publicvoidaddCorsMappings(CorsRegistryregistry){ registry.addMapping("/**"); } @Bean publicstaticPropertySourcesPlaceholderConfigurerpropertySourcesPlaceholderConfigurer(){ returnnewPropertySourcesPlaceholderConfigurer(); } @Bean publicFiltercharacterEncodingFilter(){ CharacterEncodingFiltercharacterEncodingFilter=newCharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); returncharacterEncodingFilter; } @Bean publicMappingJackson2HttpMessageConverterconverter(){ MappingJackson2HttpMessageConverterconverter=newMappingJackson2HttpMessageConverter(); returnconverter; } @Bean publicViewResolvergetViewResolver(){ InternalResourceViewResolverresolver=newInternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/jsp"); resolver.setSuffix(".jsp"); returnresolver; } @Bean publicStandardServletMultipartResolvergetStandardServletMultipartResolver(){ returnnewStandardServletMultipartResolver(); } }
4.SwaggerUI页面访问
http://localhost:8080/projectName/swagger-ui.html#!/
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。