自己配置swagger一致出错,一会儿是“Unable to infer base url”、“Unable to infer base url”等各种错误,最终发现是swagger2版本与springboot不一致后降低swagger2版本。以下是可以正常跑起来的配置
1.pom架包添加,注意swagger2版本与spring-boot版本,如果版本不一致会报错误
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--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>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2.config配置文件
package com.example.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;
/**
* SwaggerConfig的配置文件
*/
@Configuration //注入配置文件
@EnableSwagger2 //开启swagger
public class SwaggerConfig{
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//配置需要生成文件的接口文件地址
.apis(RequestHandlerSelectors.basePackage("com.example.test.controller"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger测试文档接口")
.description("后台文档")
.version("V0.0.1")
//访问域名,可以不调用这个选项
.termsOfServiceUrl("http://localhost:8080/")
.contact("名称") //
.license("")
.build();
}
}
3.案例控制器
package com.example.test.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: dev_guo
* @Date: 2022/2/7 14:06
*/
@RestController
@RequestMapping("/user")
@Api(value = "用户管理自定义类")
public class UserController {
/**
* 保存数据
* @param user
* @return
*/
@PostMapping(value = "/save")
//方法参数说明,name参数名;value参数说明,备注;dataType参数类型;required 是否必传;defaultValue 默认值
@ApiImplicitParam(name = "user", value = "新增用户数据")
//说明是什么方法(可以理解为方法注释)
@ApiOperation(value = "添加用户", notes = "添加用户")
public void save(){
System.out.println("hello save");
}
}
4.最终效果 http://localhost:8080/swagger-ui.html#