Springboot 整合Swagger 2框架 让接口查看及调试更加优雅

简介: Springboot 整合Swagger 2框架 让接口查看及调试更加优雅

先是pom.xml文件添加依赖:


    <!--swagger2-->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.8.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.8.0</version>
    </dependency>


application.yml不需要做配置

 

接着是Swagger2的配置类  Swagger2Config.java:


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 20:50 2019/5/25
 */
@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {
    /**
     * 因为 Swagger2的资源文件都是在jar包里面,如果不在此处配置加载静态资源,
     * 会导致请求http://localhost:8081/swagger-ui.html失败
     *  <!--swagger资源配置-->
     *  <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
     *  <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
     *
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.soelegant.elegantdemo.controller"))
                .paths(PathSelectors.any())
                .build()
                //不需要时,或者生产环境可以在此处关闭
                .enable(true);
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("JCccc springboot整合Swagger2项目 ")
                .description("描述:测试使用Swagger2!")
                //服务条款网址
                .termsOfServiceUrl("https://blog.csdn.net/qq_35387940")
                .contact("JCccc")
                .version("1.0")
                .build();
    }
}


然后是写一个Controller ,整合Swagger2框架注解 Swagger2TestController.java:


import com.alibaba.fastjson.JSONObject;
import com.soelegant.elegantdemo.pojo.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 20:54 2019/5/25
 */
@Api(value = "测试各种方法", tags = {"测试使用Controller"})
@RestController
public class Swagger2TestController {
    @ApiOperation(value = "测试Swagger2接口", notes = "传入编号!")
    @ApiImplicitParam(name = "id", value = "id", required = true)
    @RequestMapping(value = "/swaTest2/{id}", method = RequestMethod.GET)
    public String TestSwa2(@PathVariable("id") Integer id) {
        System.out.println("swaTest!");
        //  Optional<UserInfo> user = userRepository.findById(id);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("test");
        userInfo.setState(1);
        userInfo.setPassword("123456");
        userInfo.setNickName("testNickName");
        userInfo.setIsDeleted(id);
        userInfo.setIds(null);
        userInfo.setIdList(null);
        return userInfo.toString();
    }
    @ApiOperation(value = "swaTest3", notes = "测试GET!")
    @ApiImplicitParam(name = "name", value = "用户name")
    @RequestMapping(value = "/swaTest3", method = RequestMethod.GET)
    public String TestSwa3(@RequestParam("name") String name) {
        System.out.println("swaTest!");
        return name;
    }
    @ApiOperation(value = "swaTest4", notes = "测试POST!")
    @RequestMapping(value = "/swaTest4", method = RequestMethod.POST)
    public String TestSwa4(@RequestBody JSONObject jsonObject) {
        System.out.println("swaTest4!" + jsonObject.toString());
        String str = jsonObject.toString();
        return str;
    }
    @ApiOperation(value = "swaTest5", notes = "测试对象传值!")
    @RequestMapping(value = "/swaTest5", method = RequestMethod.POST)
    public String TestSwa5(UserInfo userInfo) {
        return userInfo.toString();
    }
}


可以看到上面的第一个接口用到了UserInfo实体类, 那么我们也将这个跟接口有关的类也结合Swagger2注解  UserInfo.java:


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 20:57 2019/5/25
 */
@Data
@ApiModel(value = "userInfo 对象",description = "用户对象user")
public class UserInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value="用户名",name="username",example="lx")
    private String username;
    @ApiModelProperty(value="状态",name="state",required=true)
    private Integer state;
    private String password;
    private String nickName;
    private Integer isDeleted;
    @ApiModelProperty(value="id数组",hidden=true)
    private String[] ids;
    private List<String> idList;
}


那么到此,我们整合Swagger2基本已经完毕,接下来看看效果:


运行项目后,进入Swagger2的接口页面:http://localhost:8099/swagger-ui.html#      (端口就是自己项目的端口,我自己的是8099)


image.png


然后可以点开接口看看,顺便还可以在线调试(点开接口,点击Try it out):


image.png


然后/swaTest4这个接口是通过@RequestBody JSONObject jsonObject 接收参数,所以在Swagger2的接口页面上,我们也传入一个json格式数据:


{

 "userName": "testName",

 "userId":"22222222"

}


如图:


image.png


点击Execute进行接口调用,可以看到接口返回:


image.png


OK,本篇springboot整合Swagger2 到此结束。


image.png

相关文章
|
安全 NoSQL Java
SpringBoot接口安全:限流、重放攻击、签名机制分析
本文介绍如何在Spring Boot中实现API安全机制,涵盖签名验证、防重放攻击和限流三大核心。通过自定义注解与拦截器,结合Redis,构建轻量级、可扩展的安全防护方案,适用于B2B接口与系统集成。
1606 3
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
925 2
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
Java Spring
聊聊你对SpringBoot框架的理解 ?
SpringBoot是Spring家族中流行的子项目,旨在简化Spring框架开发的繁琐配置。它主要提供三大功能:starter起步依赖简化依赖管理,自动配置根据条件创建Bean,以及内嵌Web服务器支持Jar包运行,极大提升了开发效率。
457 0
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
1119 8
|
监控 Kubernetes Cloud Native
Spring Batch 批处理框架技术详解与实践指南
本文档全面介绍 Spring Batch 批处理框架的核心架构、关键组件和实际应用场景。作为 Spring 生态系统中专门处理大规模数据批处理的框架,Spring Batch 为企业级批处理作业提供了可靠的解决方案。本文将深入探讨其作业流程、组件模型、错误处理机制、性能优化策略以及与现代云原生环境的集成方式,帮助开发者构建高效、稳定的批处理系统。
1102 1
|
安全 Java 微服务
Java 最新技术和框架实操:涵盖 JDK 21 新特性与 Spring Security 6.x 安全框架搭建
本文系统整理了Java最新技术与主流框架实操内容,涵盖Java 17+新特性(如模式匹配、文本块、记录类)、Spring Boot 3微服务开发、响应式编程(WebFlux)、容器化部署(Docker+K8s)、测试与CI/CD实践,附完整代码示例和学习资源推荐,助你构建现代Java全栈开发能力。
1271 1
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
627 0
|
Cloud Native Java API
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
1998 0