springboot2.6.x版本以上配置swagger3.0会提示空指针异常,今天单独整理一下完整的配置方案。

1.引入依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2.yml文件添加配置

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

3.创建swagger配置文件

@Configuration
@EnableOpenApi
public class Swagger {
    /**
     *   application中还配置了mvc,因为springboot2.6.1与swagger3不兼容
     */

    /**
     * ture 启用Swagger3.0, false 禁用(生产环境要禁用)
     */
    Boolean swaggerEnabled=true;
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                // 是否开启
                .enable(swaggerEnabled)
                .select()
                // 扫描的路径使用@Api的controller
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("社区交互软件接口文档")
                //作者信息
                .contact(new Contact("xxx","https://xxx.icu/", "xxx@qq.com"))
                .version("1.0")
                .build();
    }






}

4.添加注解

4.1 controller添加注解

@RestController
@RequestMapping("/users")
@Api(tags = "用户模块")
public class UserController {
    static Map<Long,User> users = Collections.synchronizedMap(new HashMap<>());


    @GetMapping("/")
    @ApiOperation(value = "查询所有的用户信息")
    public List<User> getUserList(){
        return new ArrayList<User>(users.values());
    }

4.2 实体类添加注解

@Data
@ApiModel(value = "user",description = "用户属性")
public class User {

    @ApiModelProperty(value = "主键")
    private Long id;
    @ApiModelProperty(value = "姓名")
    private String name;
    @ApiModelProperty(value = "年龄")
    private Integer age;
}

5.访问  

3.0之后的访问地址变了,这里需要注意。

新地址:http://localhost:8080/swagger-ui/

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐