io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
二.配置yml(SpringBoot版本较高时)
SpringBoot2.6.x的版本中SpringMVC默认路径匹配策略从ANT_PATH_MATCHER变更为PATH_PATTERN_PARSER 进而导致无法访问swagger-ui.html
spring:
#springboot2.6.x的版本中springmvc默认路径匹配策略从ANT_PATH_MATCHER变更为PATH_PATTERN_PARSER 进而导致无法访问swagger-ui.html
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
三.代码部分
Config
@Configuration
@EnableSwagger2//开启Swagger
@Profile("dev")//设置于何环境下生效
public class SwaggerConfig {
@Bean//配置swagger的Docket的Bean实例
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("alan")//设置分组
.apiInfo(setApiInfo())//设置作者信息
.select()//设置扫描对象的方式
// .apis(RequestHandlerSelectors.扫描方式) 设置需要扫描的对象及扫描的方式
// 扫描方式:
// basePackage(包路径) 扫描包下所有类
// withMethodAnnotation(注解.class) 扫描有该注释的方法
// withClassAnnotation(注解.class) 扫描有该注释的类
// any() 扫描所有controller
// none() 不进行扫描
.apis(RequestHandlerSelectors.basePackage("com.alan.springboot.Controller"))
// .paths(PathSelectors.过滤方式) 设置需要过滤的对象及过滤的方式
// 过滤方式:
// ant()路径 any()任何接口 none()不过滤 regex()正则表达式
.build();//对应select()
}
//作者联系方式
Contact contact = new Contact("alan", "none", "none");
//Swagger信息配置
public ApiInfo setApiInfo() {
return new ApiInfo(
"用户管理系统",//标题
"用户管理系统文档",//描述
"1.0",//版本
"urn:tos",//免责条款
contact,//作者信息
"Apache 2.0",//版本许可证
"http://www.apache.org/licenses/LICENSE-2.0",//许可证地址
new ArrayList()//扩展
);
}
//其他Swagger分组
@Bean
public Docket docketA(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docketB(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docketC(){
return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}
}
Swagger信息的配置可参照ApiInfo的构造方法
POJO及Controller注:POJO及Controller中均可对Swagger对应模块进行注释
@Data
@Getter
@Setter
@ApiModel("用户实体类")//module注释(swagger注解)
public class User {
@ApiModelProperty("用户ID")//module属性注释
public String ID;
@ApiModelProperty("用户名")
public String UserName;
@ApiModelProperty("密码")
public String Password;
@ApiModelProperty("权限")
public String Perms;
@ApiModelProperty("角色")
public String Role;
}
@RestController
@RequestMapping("/RESTful")
@Api(tags = "用户管理系统",description = "这是描述")//设置接口名 tags属性将会覆盖value属性(swagger注解)
public class SwaggerController {
@Autowired
UserServiceImpl userService;
@GetMapping
@ApiOperation("查询用户")//设置方法名(swagger注解)
public List getUserInformation(){
return userService.getUserInformation();
}
@PostMapping
@ApiOperation("新增用户")//设置方法名(swagger注解)
public void insertUser(User user){
userService.insertUser(user);
}
@PutMapping
@ApiOperation("修改用户")//设置方法名(swagger注解)
public void updataUser(User user){
userService.updataUser(user);
}
@DeleteMapping("/{id}")
@ApiOperation("删除用户")//设置方法名(swagger注解)
public void deleteUser(@PathVariable("id") int id){
userService.deleteUser(id);
}
}
运行效果
访问localhost:8080/swagger-ui.html
可以看到,在Config中设置的ApiInfo、作者联系方式等配置均生效
点开下方被扫描如Swagger的接口,可以看到在POJO及Controller中设置的注释均生效
在右上角切换至其他分组,由于未进行扫描配置,默认扫描所有对象。可以看到所有的Controller类都被扫描进该分组



