SpringBoot使用swagger3构建API文档

本文介绍了在Spring Boot项目中集成Swagger框架的方法。包括在pom.xml添加依赖、创建Swagger配置类、对Application和Controller添加swagger注解等步骤,还列举了Swagger常用注解。此外,针对Spring Boot 2.6.x以上版本与Swagger 3.0.0整合及开启SpringSecurity后可能出现的异常给出了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Swagger是一个方便我们更好编写API文档的框架,而且Swagger可以模拟http请求调用。

Swagger官网:Springfox Reference Documentation

一、pom.xml添加依赖

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

二、Swagger配置类

需要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("对外开放接口API 文档")
                .description("HTTP对外开放接口")
                .version("1.0.0")
                .termsOfServiceUrl("http://xxx.xxx.com")
                .license("LICENSE")
                .licenseUrl("http://xxx.xxx.com")
                .build();
    }
}

用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。

全局配置 header 请求参数

设置 globalRequestParameters 参数信息开启header请求参数

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .globalRequestParameters(getGlobalOperationParameters())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demo.hello.interfaces.facade"))
                .build();
    }

    private List<RequestParameter> getGlobalOperationParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("token")
                .description("认证token")
                .in(ParameterType.HEADER)
                .required(false)
                .build());
        return parameters;
    }
}

​​​​​​​  

三、对Application和Controller添加swagger注解

Application.java 加上注解@EnableSwagger2 表示开启Swagger

@SpringBootApplication
@EnableSwagger2
public class Helloworld01Application {
    public static void main(String[] args) {
        SpringApplication.run(Helloworld01Application.class, args);
    }
}

启动SpringBoot项目,访问http://127.0.0.1:8080/swagger-ui/

对controller添加接口的swagger支持

@Api(value = "/api", tags = "测试API接口")
@RestController
@RequestMapping("/api")
public class ScoreController {

    @Autowired
    private ScoreService service;

    @ApiOperation(value = "获取得分列表", notes = "详细描述")
    @RequestMapping(value = "/getScore", method = RequestMethod.GET)
    public void GetScore(@RequestParam("uid") @ApiParam(name="uid", value="用户ID") String uid){
        List<Score> scorelist = service.SelScoreList(uid);
        this.renderSuccess(scorelist);
    }
}

Swagger注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

· @Api:修饰整个类,描述Controller的作用

· @ApiOperation:描述一个类的一个方法,或者说一个接口

· @ApiParam:单个参数描述

· @ApiModel:用对象来接收参数

· @ApiProperty:用对象接收参数时,描述对象的一个字段

· @ApiResponse:HTTP响应其中1个描述

· @ApiResponses:HTTP响应整体描述

· @ApiIgnore:使用该注解忽略这个API

· @ApiError :发生错误返回的信息

· @ApiImplicitParam:一个请求参数

· @ApiImplicitParams:多个请求参数

解决异常报错:

(1)当Spring Boot 2.6.x以上版本 和 Swagger 3.0.0 整合的时候,可能会报错如下所示:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

解决方案:

在application.properties中添加:

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

(2)开启SpringSecurity后swagger-ui无法正常访问

解决方案:

修改WebSecurity配置


@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    public static final String[] permitMethods=new String[]{
            "/swagger-ui/**",
            "/swagger-resources/**",
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭跨站请求防护
                .cors().and().csrf().disable()
                //允许不登陆就可以访问的方法,多个用逗号分隔
                .authorizeRequests().antMatchers(permitMethods).permitAll()
                //其他的需要授权后访问
                .anyRequest().authenticated()

                .and()
                //增加是否登陸过滤
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                // 前后端分离是无状态的,所以暫時不用session,將登陆信息保存在token中。
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值