最近两天一直在搞Swagger,Swagger让接口开发测试变得简单很多,不用像postman那样还要输入链接,选择请求方式等
关于整合Swagger大致上需要两步骤,第一步就是pom文件引入依赖包
<!-- SpringBoot整合Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<!--
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.7.0</version>
</dependency> -->
<!-- swagger-ui自定义页面 -->
第二步就是添加配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket api_lf(){
return new Docket(DocumentationType.SWAGGER_2)
//.groupName("api_lf")
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
/**
* 构建api文档详细信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("慢慢人生路")
.description("个人基础数据")
.termsOfServiceUrl("http://blog.youkuaiyun.com/catoop/article/details/50668896")
.contact("david")
.version("1.0")
.build();
}
}
正两部结束之后基本就行的通了,浏览器访问链接:http://localhost:port/life/swagger-ui.html
就可以切身感受下Swagger带来的便捷与美感了
然而现实总不是那么一帆风顺的,刚开始的时候,做好这两步之后,访问Swagger并没有出现我定义的controller信息,打开console也是一对404;百度了一下,有的说是什么Swagger要加载静态资源文件,要配这个配那个的,试了也都没效果;最后的解决方案是我检查了下pom文件,发现没有整合到mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>版本号
</dependency>
即如上这个依赖包没有添加进去,这是临时弄的一个spring boot特地来测试Swagger的,但是为了测试是不是这个问题,我又把这个依赖包注释掉了,但是还是能正常访问Swagger,以后有时间再去细究吧,可能之前捣鼓了半天不知怎么就搞好了,在此记录下这个问题