Swagger2在spring拦截器的配置及全局参数设置

本文详细介绍了如何在SpringBoot项目中配置Swagger2,包括自定义全局参数、响应码及实现请求拦截,确保API文档的完整性和安全性。

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

一:配置拦截器

默认拦截器是对Swagger2请求时拦截的。

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {



    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置登录拦截器
        registry.addInterceptor(new AuthorizedCheckInterceptor()).
                addPathPatterns("/**")
                    .excludePathPatterns("/users/login/**", "/swagger-resources/**", "/webjars/**", "/swagger-ui.html/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将templates目录下的CSS、JS文件映射为静态资源,防止Spring把这些资源识别成thymeleaf模版
        //  registry.addResourceHandler("/templates/**.js").addResourceLocations("classpath:/templates/");
        //registry.addResourceHandler("/templates/**.css").addResourceLocations("classpath:/templates/");
        //其他静态资源
        //registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //swagger增加url映射
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

二 配置全局参数

如配置所有请求header中需要添加token,配置全局响应码

package org.niugang.coding.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * 接口文档
 *
 * @author Created by niugang on 2018/12/28/15:10
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 全局参数(如header中的token)
     *
     * @return List<Parameter>
     */
    private List<Parameter> parameter() {
        List<Parameter> params = new ArrayList<>();
        params.add(new ParameterBuilder().name("token")
                .description("请求令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false).build());
        return params;
    }

    @Bean
    public Docket sysApi() {
        //设置全局响应状态码
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(404).message("找不到资源").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(400).message("参数错误").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(401).message("没有认证").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(403).message("没有没有访问权限").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(200).message("请求成功").responseModel(new ModelRef("ApiError")).build());

        return new Docket(DocumentationType.SWAGGER_2)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .apiInfo(apiInfo())
                .select()
                 //默认显示所有controller
                .apis(RequestHandlerSelectors.basePackage("org.niugang.coding"))
                .paths(PathSelectors.any())
                .build().globalOperationParameters(parameter());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("new-coding-standards-user")
                .description("springboot新代码规范脚手架工程")
                .termsOfServiceUrl("")
                .contact(new Contact("niugang", "", "863263957@qq.com"))
                .version("1.0")
                .build();
    }

}

                                                                        微信公众号

                                               

                                                                             JAVA程序猿成长之路

                          分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。 

### 如何在 Swagger设置请求参数为必填项 在 Swagger配置中,可以通过多种方式来定义请求参数是否为必填项。以下是几种常见的实现方法: #### 方法一:通过 `@ApiModelProperty` 注解 当使用 DTO 对象作为请求体时,可以在对象的字段上添加 `@ApiModelProperty` 注解,并将其属性 `required` 设置为 `true` 来指定该字段为必填项[^1]。 ```java public class AppNoticeVo { @ApiModelProperty(value = "自建应用的corpid", required = true) private String corpid; // Getter and Setter methods... } ``` 上述代码表示 `corpid` 字段是一个必需的参数。 --- #### 方法二:通过 `@ApiParam` 注解 对于控制器中的单个参数,可以使用 `@ApiParam` 注解并设置其 `required` 属性为 `true`,从而标记此参数为必填项[^3]。 ```java @PostMapping("/createUser") public ResponseEntity<String> createUser( @ApiParam(value = "用户名", required = true) @RequestParam String username, @ApiParam(value = "密码", required = true) @RequestParam String password) { // 处理逻辑... return ResponseEntity.ok("Success"); } ``` 在此示例中,`username` 和 `password` 参数都被设为必填项。 --- #### 方法三:通过 `@ApiImplicitParams` 和 `@ApiImplicitParam` 注解 如果需要在一个接口中定义多个请求参数及其约束条件,则可以使用 `@ApiImplicitParams` 和 `@ApiImplicitParam` 组合注解。 ```java @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer"), @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String"), @ApiImplicitParam(name = "email", value = "邮箱地址", required = false, dataType = "String") }) @PostMapping("/updateUser") public ResponseEntity<String> updateUser(@RequestParam Map<String, Object> params) { // 处理逻辑... return ResponseEntity.ok("Update Success"); } ``` 在这个例子中,`id` 和 `name` 是必填参数,而 `email` 则是非必填参数。 --- #### 方法四:全局校验支持 为了进一步增强对请求参数的验证能力,在 Spring Boot 项目中通常会结合 Hibernate Validator 或其他类似的工具来进行全局校验[^4]。例如,可以直接在实体类或 DTO 类中加入 JSR 380 标准的注解(如 `@NotNull`, `@NotBlank` 等),这些注解不仅会影响业务逻辑层的行为,还会被 Swagger 自动识别并展示出来。 ```java public class CreateUserRequest { @NotBlank(message = "用户名不能为空") private String username; @Size(min = 6, max = 20, message = "密码长度应在6到20之间") private String password; // Getter and Setter methods... } ``` 此时无需额外操作即可让 Swagger UI 显示对应的必填提示信息。 --- ### 注意事项 - 如果某些参数不需要显示在文档中或者不希望对其进行任何校验,可考虑使用 `@ApiIgnore` 将它们排除在外[^2]。 - 当前版本的 Swagger 已经逐渐迁移到 OpenAPI 规范下,因此建议开发者关注最新官方指南以获取更全面的支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值