说明:
(1)Swagger的主要作用是【生成API文档】;而且,当我们项目更新的时候,Swagger也会实时更新;
目录
2.在程序入口处MallApplication,使用【@EnableSwagger2注解】:开启Swagger;
3.创建SpringFoxConfig类,去配置Swagger;
4.创建ImoocMallWebMvcConfig类,去配置地址映射;
1.访问Swagger文档地址;然后,可以通过【@ApiOperation("接口描述信息")】去说明,接口的基本信息;
2.可以在Swagger文档页上,调试接口;(所以,这个Swagger文档页,可以当成postman来用)
一:引入并配置Swagger;
1.在pom.xml中,引入Swagger所需的依赖;
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
说明:
(1)依赖说明;
2.在程序入口处MallApplication,使用【@EnableSwagger2注解】:开启Swagger;
3.创建SpringFoxConfig类,去配置Swagger;
SpringFoxConfig类:
package com.imooc.mall.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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; @Configuration public class SpringFoxConfig { //访问http://localhost:8083/swagger-ui.html可以看到API文档 @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("慕慕生鲜") .description("") .termsOfServiceUrl("") .build(); } }
说明:
(1)这个配置文件,一般是不需要我们自己去写的;其是一个模板化代码,以后当我们需要的时候,直接过来copy就行了,然后再根据我们的需要微调即可;
4.创建ImoocMallWebMvcConfig类,去配置地址映射;
package com.imooc.mall.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 描述: 配置地址映射 */ @Configuration public class ImoocMallWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); } }
说明:
(1)这儿又一次使用到了【@Configuration注解】,说明这个类是个配置类;;;;第一次遇到【@Configuration注解】是在【Spring IoC容器与Bean管理25:使用Java Config方式实现Spring IoC一:对象实例化;(@Configuration,@Bean)】;
(2)配置内容分析;
(3)这儿的内容,也没必要记忆,需要的时候,过来copy就行了;
二:使用Swagger;
1.访问Swagger文档地址;然后,可以通过【@ApiOperation("接口描述信息")】去说明,接口的基本信息;
启动项目;然后访问我们在SpringFoxConfig中配置的【http://localhost:8083/swagger-ui.html】这个地址;
可以看到,项目中所有的url对外暴露的接口,给收集到这儿;那么以后,如果我们要和其他人进行文档交互的时候,我们直接提供 【http://localhost:8083/swagger-ui.html】这个地址,对方就能知道我们有哪些接口了;
我们可以在接口上,使用【@ApiOperation("接口描述信息")】去说明,接口的基本信息;
重启项目,刷新页面:
2.可以在Swagger文档页上,调试接口;(所以,这个Swagger文档页,可以当成postman来用)
……………………………………………………