
SpringBoot整合Swagger2实战
导入必要的Swagger包和Spring注解。
发布日期: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
,完成以下步骤:
@EnableSwagger2public 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
中:
@Configurationpublic 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() { ListresMsgList = 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
查看文档。
本文中的配置文件和依赖项均基于实际项目需求进行了优化和调整,确保可用性和实用性。
发表评论
最新留言
表示我来过!
[***.240.166.169]2025年05月07日 20时52分01秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
PHP实现异步定时多任务消息推送
2023-01-23
回溯法介绍
2023-01-23
非对称加密算法——SIDH加密算法的深度分析与应用探索
2023-01-23
有了Trae,人人都是程序员的时代来了
2023-01-23
公共课计算机总复习 核心知识点(1)
2023-01-23
史上最全40道Dubbo面试题!
2023-01-23
上下文无关文法
2023-01-23
STM8的C语言编程(14)--+PWM
2023-01-23
SpringBoot 学习笔记完整教程4
2023-01-23
【颠覆传统】Android锁屏界面全新重构:深度解析SystemUI横竖屏智能适配秘诀
2023-01-23
Servlet的三个基本方法
2023-01-23
AI驱动的企业信用评级模型可解释性增强系统
2023-01-23
政务服务小程序代码实战:数字政府与智慧政务全攻略
2023-01-23
反 TypeScript
2023-01-23
微信小程序wx.previewImage实现图片预览
2023-01-23
数据分析与处理方法
2023-01-23
如何通过 WebSockets 实现 Python 和 JavaScript 的实时通信
2023-01-23
程序员的幽默10
2023-01-23