SpringMvc整合Swagger(spring版本在4.1.8以上膘滨,深深的痛)
1.先搭建好springmvc的環(huán)境
2.修改pom文件
<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>
3.也需要引入jackson的包
4.定義一個swagger的配置類
@EnableWebMvc
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("jk.zmn.mvc.controller")) //要掃描的API(Controller)基礎包
.paths(PathSelectors.any()) // and by paths
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口列表 v1.1.0") // 任意干旧,請稍微規(guī)范點
.description("接口測試") // 任意蝠引,請稍微規(guī)范點
.termsOfServiceUrl("http://localhost:8080/swagger-ui.html") // 將“url”換成自己的ip:port
.contact("laowu") // 無所謂(這里是作者的別稱)
.version("1.1.0")
.build();
}
}
5.修改springmvc的配置文件,放行一些靜態(tài)資源
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
<!--<!– 添加掃描配置類 –>-->
<bean class="jk.zmn.mvc.config.SwaggerConfig" />
6.新建controller跋理,定義一些相關的文檔
@RestController
@RequestMapping("test")
@Api(value = "Test")
public class TestController {
@RequestMapping("index")
@ApiOperation(value = "進入首頁面")
public String index(){
return "index";
}
}
7.訪問http://ip:端口/項目名/swagger-ui.html即可
SpringBoot整合swagger
1.新建springboot項目
2.引入swagger的jar包
<!-- Swagger -->
<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>
3.定義swagger的配置類
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("jk.zmn.swaggerspringboot.controller")) //要掃描的API(Controller)基礎包
.paths(PathSelectors.any()) // and by paths
.build()
.apiInfo(buildApiInf());
}
private ApiInfo buildApiInf() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2 UI構建API文檔")
.contact("test")
.version("1.0.0")
.build();
}
}
4.自定義controller生成文檔
5.訪問http://ip:端口/項目名/swagger-ui.html即可