导入依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
创建HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
在启动项目时报错,Failed to start bean ‘documentationPluginsBootstrapper
在application.properties中添加
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
启动项目,访问http://localhost:8080/swagger-ui/index.html
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact contact = new Contact("阿强", "https://blog.csdn.net/qq_41505957", "1758043090@qq.com");
return new ApiInfo("我的API文档",
"阿强的swagger文档",
"v1.0",
"https://blog.csdn.net/qq_41505957",// 自己的团队组织网站
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
}
}
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).
select().
apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")).
build();
}
使用groupName()为api文档分组。
当想创建多个分组时,需要创建多个Docket Bean
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).
groupName("阿强").
select().
apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")).
build();
}
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).
groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).
groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).
groupName("C");
}
创建一个实体类,@ApiModel用于实体类上
@ApiModelProperty用于实体类属性上
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
private String userName;
@ApiModelProperty("密码")
private String passWord;
public User(String userName, String passWord) {
this.userName = userName;
this.passWord = passWord;
}
}
当实体类作为方法的返回值时,文档中会有实体类的说明
@GetMapping("/getUser")
public User getUser(User user){
return user;
}