Spring Boot集成Swagger可以自動生成項目的接口文檔及在線調試,方便快捷,因此越來越受到程序員的關注。其具體集成步驟如下:
一、定義Swagger配置bean
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("在SpringBoot項目結合Swagger編寫接口文檔")
.description("Swagger官方倉庫https://github.com/swagger-api/swagger-ui")
.termsOfServiceUrl("https://github.com/forgot2015")
.version("1.0")
.build();
}
}
注:其中ApiInfo中的title是Swagegr網頁內部的標題,description是位於標題下面的描述信息,termsOfServiceUrl是一個url連接(可以用來鏈接項目首頁),version是項目版本信息。
二、SpringBoot項目啓動類增加啓動Swagger
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
三、設置Swagger下的bean屬性
@ApiModel(value = "用戶信息",description = "這裏包含用戶的信息")
public class User implements Serializable {
@ApiModelProperty(value = "用戶名",example = "forgot2015")
private String name;
@ApiModelProperty(value = "用戶密碼",example = "123456")
private String password;
@ApiModelProperty(value = "年齡",example = "18")
private Long age;
public User(String name, String password, Long age) {
this.name = name;
this.password = password;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
這裏使用了@ApiModel與@ApiModelProperty註解
四、Swagger UI頁面打開
瀏覽器下輸入ip:port/swagger-ui.html,如下: