今天遇到跟同事遇到一個由于失誤導致的問題,也可以說比較難發現了.在此記錄一下(我們用的springboot是2.0.3,swagger是2.2.2)
問題描述:
swagger修改title,description等都不生效。并且啟動springboot,沒有有去加載swagger的配置類。(在debug模式啟動)
經過不斷的查找,發現了原因是:swagger的配置類的注解加錯了。@Configuration不小心寫成了@Configurable.
還有就是@EnableSwagger2注解只需要加在swagger配置類上
springboot引入swagger2的步驟:
①引入依賴
<!-- 引入swagger包 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
②編寫Swagger2的配置類
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo getApiInfo(){
return new ApiInfoBuilder()
.title("Swagger2....")
.description("Swagger2")
.version("1.0")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
.build();
}
}
③在controller中添加注解:按需添加注解
@Controller
@RequestMapping("/user")
@Api(tags = "我的接口模塊")
public class UserController {
@Autowired
private UserService userService;
//注意這個注解跟請求對應的@XxxMapping,要不然這個接口會生成好多方法
@GetMapping(value = "/getUserById")
@ResponseBody
@ApiOperation(value = "根據ID查詢User")
public User getUserById(@RequestParam(value = "id") int id){
return userService.getUserById(id);
}
}
④在model(pojo)上加注解,按需添加
@ApiModel(value = "用戶對象")
public class User {
@ApiModelProperty(value = "用戶ID", name = "userId")
private Integer userId;
@ApiModelProperty(value = "用戶姓名",name = "userName")
private String userName;
@ApiModelProperty(value = "用戶密碼",name = "password")
private String password;
@ApiModelProperty(value = "用戶手機號",name = "phone")
private String phone;
一些注解的使用
@Api:一般用于Controller中,用于接口分組
@ApiOperation:接口說明,用于api方法上。
@ApiImplicitParams:用在方法上包含一組參數說明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數的各個方面
paramType:參數放在哪個地方
header 請求參數的獲取:@RequestHeader
query 請求參數的獲取:@RequestParam
path(用于restful接口) 請求參數的獲取:@PathVariable
body(不常用)
form(不常用)
name:參數名
dataType:參數類型
required:參數是否必須傳
value:參數的意思
defaultValue:參數的默認值
@ApiResponses:用于表示一組響應
@ApiResponse:用在@ApiResponses中,一般用于表達一個錯誤的響應信息
code:數字,例如400
message:信息,例如”請求參數沒填好”
response:拋出異常的類
@ApiModel:描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam注解進行描述的時候)表明這是一個被swagger框架管理的model,用于class上
@ApiModelProperty :使用在實體類上的成員變量上,描述成員變量的含義。
以上就是解決springboot引入swagger2不生效問題的詳細內容,更多關于springboot引入swagger2的資料請關注html5模板網其它相關文章!