SpringBoot整合Swagger2实战
发布日期:2021-05-24 13:14:40 浏览次数:23 分类:精选文章

本文共 7800 字,大约阅读时间需要 26 分钟。

Springfox Swagger Swagger2配置与应用说明

一、依赖项配置

本项目基于Springfox Swagger2框架进行接口文档配置,以下是相关依赖项:

io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2

二、配置文件创建

创建Swagger配置文件SwaggerConfig.java,完成以下步骤:

  • 导入必要的Swagger包和Spring注解。
  • @EnableSwagger2
    public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo()) // 调用apiInfo()方法获取_apiInfo信息
    .select() // 配置扫描策略
    .apis(RequestHandlerSelectors.basePackage("com.litewms.front.controller")) // 配置扫描的包路径
    .paths(PathSelectors.any()) // 配置接口路径策略
    .build();
    }
    @Bean
    private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
    .title("轻量级仓库管理系统") // API标题
    .description("轻量级仓库管理系统API文档") // API描述
    .contact(new Contact("系统管理员", "", "admin@example.com")) // API联系人信息
    .version("v1.0.0") // API版本号
    .build();
    }
    }

    三、静态资源映射配置

    完成静态资源映射,添加以下配置到WebMvcConfig.java中:

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/swagger-ui.html") // Swagger UI映射路径
    .addResourceLocations("classpath:/META-INF/resources/"); // 资源路径设置
    registry.addResourceHandler("/webjars/**") // Webjars资源映射
    .addResourceLocations("classpath:/META-INF/resources/webjars/"); // 资源路径设置
    }
    }

    四、安全配置

    如果使用JWT或其他安全框架,需要在安全配置文件中放行相关路径。例如:

    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserInfoServiceImpl userInfoService;
    @Autowired
    private JwtAuthorizationTokenFilter jwtAuthorizationTokenFilter;
    @Autowired
    private TokenLoginFilter tokenLoginFilter;
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userInfoService)
    .passwordEncoder(passwordEncoderBean());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
    .exceptionHandling()
    .authenticationEntryPoint(jwtAuthenticationEntryPoint)
    .and()
    .csrf().disable() // 禁用跨文本请求伪造
    .authorizeRequests()
    .antMatchers("/login/**").permitAll() // 登录路径放行
    .antMatchers("/swagger-ui.html").permitAll() // Swagger UI路径放行
    .antMatchers("/webjars/**").permitAll() // Webjars路径放行
    .antMatchers("/swagger-resources/**").permitAll() // Swagger资源路径放行
    .antMatchers("/v2/*").permitAll() // v2 API路径放行
    .antMatchers("/csrf").permitAll() // 放行csrf路由
    .antMatchers(HttpMethod.OPTIONS, "/**").anonymous() // OPTIONS请求提 ZahNeutral
    .anyRequest().authenticated()
    .and()
    .addFilterAt(tokenLoginFilter, UsernamePasswordAuthenticationFilter.class) // 添加Token登录过滤器
    .addFilterAfter(jwtAuthorizationTokenFilter, TokenLoginFilter.class) // 添加JWT过滤器
    .httpBasic();
    }
    @Bean
    public PasswordEncoder passwordEncoderBean() {
    return new BCryptPasswordEncoder();
    }
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();
    }
    }

    五、注解使用说明

    1. Controller注解

    在Controller类中使用@RestController@RequestMapping注解,例如:

    @Api(tags = "入库申请表")
    @RestController
    @RequestMapping("/front/inapply")
    public class InApplyController {
    @Autowired
    private InApplyService inApplyService;
    @ApiOperation(
    value = "获取入库申请表", // 操作说明
    notes = "获取入库申请表的功能", // 达到说明
    response = InApply.class, // 返回类型
    httpMethod = "GET" // HTTP方法
    )
    @RequestMapping("/list")
    public R list() {
    return R.ok();
    }
    }

    2. 方法注解

    在方法中使用@ApiOperation@ApiImplicitParam等注解,例如:

    @ApiImplicitParams({
    @ApiImplicitParam(
    name = "id",
    value = "参数说明",
    required = true,
    paramType = "path",
    dataType = "Integer",
    example = "12345"
    )
    })
    @ApiResponses({
    @ApiResponse(code=404, message = "资源不存在")
    })
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
    return R.ok();
    }

    3. Model注解

    在实体类中使用@ApiModel@ApiModelProperty注解,例如:

    @ApiModel(value = "用户申请表", description = "用户申请表的详细信息")
    @Data
    @Table(name = "tb_in_apply")
    public class InApply implements Serializable {
    private static final Long serialVersionUID = 1L;
    @ApiModelProperty(value = "主键", required = true, dataType = "int")
    @TableId(type = IdType.AUTO)
    private Integer id;
    @ApiModelProperty(value = "流水号")
    private String serialNo;
    @ApiModelProperty(value = "状态")
    private Byte status;
    @ApiModelProperty(value = "创建人")
    private Integer createBy;
    @ApiModelProperty(value = "更新人")
    private Integer updateBy;
    @ApiModelProperty(value = "创建时间")
    private Date createTime;
    @ApiModelProperty(value = "更新时间")
    private Date updateTime;
    @ApiModelProperty(value = "回收站标志")
    private String deleted;
    }

    六、全局返回码配置

    在Swagger配置文件中,添加全局返回码配置:

    @Configuration
    @ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
    public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
    List
    resMsgList = Arrays.asList(
    new ResponseMessageBuilder().code(200).message("成功!").build(),
    new ResponseMessageBuilder().code(-1).message("未知错误,请联系管理员!").build(),
    new ResponseMessageBuilder().code(10001).message("参数校验错误!").build(),
    new ResponseMessageBuilder().code(10002).message("请求方法错误!").build(),
    new ResponseMessageBuilder().code(10003).message("查询结果为空!").build(),
    new ResponseMessageBuilder().code(10004).message("对象不能为空!").build(),
    new ResponseMessageBuilder().code(20001).message("用户不存在!").build(),
    new ResponseMessageBuilder().code(20002).message("超级管理员账号无法删除!").build(),
    new ResponseMessageBuilder().code(20003).message("用户已存在!").build(),
    new ResponseMessageBuilder().code(20004).message("登录验证失败,请检查用户名或密码!").build(),
    new ResponseMessageBuilder().code(20005).message("尚未登录!").build()
    );
    return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo())
    .select()
    .apis(RequestHandlerSelectors.basePackage("ams.web.ams.controller"))
    .paths(PathSelectors.any())
    .build()
    .globalResponseMessage(RequestMethod.GET, resMsgList)
    .globalResponseMessage(RequestMethod.POST, resMsgList)
    .globalResponseMessage(RequestMethod.PUT, resMsgList)
    .globalResponseMessage(RequestMethod.DELETE, resMsgList);
    }
    private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
    .title("智慧档案管理系统后台API")
    .contact(new Contact("系统管理员", "", "admin@example.com"))
    .version("v1.0.0")
    .description("API 描述")
    .build();
    }
    }

    七、注意事项

  • 在正式环境中,建议关闭Swagger2,以减少潜在的安全风险。

  • 根据实际项目需求,调整配置参数,例如模块扫描路径和安全规则。

  • 如使用JWT或其他安全框架,需在SecurityConfig中放行相应路径以允许 Swagger-UI 访问。

  • 确保项目启动后访问http://localhost:8080/swagger-ui.html查看文档。

  • 本文中的配置文件和依赖项均基于实际项目需求进行了优化和调整,确保可用性和实用性。

  • 上一篇:SpringSecurity整合jwt权限认证全流程解析
    下一篇:SpringSecurity报错authenticationManager must be specified

    发表评论

    最新留言

    表示我来过!
    [***.240.166.169]2025年05月07日 20时52分01秒