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,如下: