SpringBoot整合Swagger2实践

 

关于 Swagger

Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:

  • Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API
  • Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
  • Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
  • Swagger 有一个强大的社区,里面有许多强悍的贡献者

Swagger的缺点

Swagger是一个非常强大的文档工具,但是对代码侵入性太高,这点等会截图下来,大家就可以看到的,这个点是缺陷,也导致了很多公司并没有使用他,当然使用他并没有什么坏处

 

使用swagger就造成了文档和代码在一起了,一般这不是我们愿意看到的,我们希望代码就是纯粹的项目代码,而文档就是纯粹的文档.

 

综合分析swagger

  在开发中我们构建RESTful风格Api时候就可能需要面对不同的开发前端,例如微信小程序,app,web,安卓,ios,那么我们就需要一份开发文档给前端人员进行调用,在之前笔者是采用showdoc进行构建的,就是石墨文档,还有自己内部的服务器进行写文档的,这个给笔者开发带了很大的麻烦,一个上午的时间只可以写四个文档,对每个参数进行说明,

  同时,在开发过程中如果代码修改,参数类型发生改变,还有请求类型发送改变,那么就需要去重新修改文档,这个给开发效率造成了很大的麻烦,swagger是一个很好的开发工具,

 

springboot整合swagger

 

  1. 添加依赖:
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>

 

  1. 添加swagger2的配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.service.ApiInfo;



@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
               .apis(RequestHandlerSelectors.basePackage("com.curefun.vspmanager.dataimport.controller"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("项目使用")
                .termsOfServiceUrl("陈秀峰")
                .contact("陈秀峰")
                .version("1.0")
                .build();
    }


}
 

重要的设置就是: basePackage 需要换成自己项目的controller 所在的包名字

 

通过@Configuration注解,让Spring-boot来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2Config
再通过createRestApi方法创建DocketBean之后,
apiInfo方法用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
select() 函数返回一个 ApiSelectorBuilder 实例用来控制哪些接口暴露给Swagger2来展现。
一般采用指定扫描的包路径来定义
Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)

 

 

  1. 编写controller
@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {


    @PostMapping("/")
    @ApiOperation("添加用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
            @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
    }
    )
    public String addUser(String username, @RequestParam(required = true) String address) {

        return "success";

    }



    @GetMapping("/")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }


    @PutMapping("/{id}")
    @ApiOperation("根据id更新用户的接口")
    public User updateUserById(@RequestBody User user) {
        return user;
    }

}
 
  1. 配置实体类

 

其中的User实体类为:

@ApiModel
public class User {

    @ApiModelProperty(value = "用户id")
    private Integer id;

    @ApiModelProperty(value = "用户名")
    private String username;

    @ApiModelProperty(value = "用户地址")
    private String address;

    //getter/setter
}

 

 

 

  1. 访问接口

http://localhost:8080/swagger-ui.html

Swagger注解

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

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponseHTTP响应其中1个描述
  • @ApiResponsesHTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数

 

 

Security中的配置

如果我们的Spring Boot项目中集成了Spring Security,那么如果不做额外配置,Swagger2文档可能会被拦截,此时只需要在Spring Security的配置类中重写configure方法,添加如下过滤即可:

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()            
.antMatchers("/swagger-ui.html").antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现springboot整合swagger2 3.0.0版本,你需要按照以下步骤操作: 1. 创建一个maven项目并引入spring-boot-starter-web和springfox-boot-starter依赖。在pom.xml文件中添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- <version>2.5.6</version> --> <!-- <version>2.6.3</version> --> <!-- <version>2.6.5</version> --> <version>2.7.3</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.26</version> </dependency> ``` 2. 在application.yml配置文件中添加以下内容: ```yaml spring: mvc: pathmatch: matching-strategy: ant_path_matcher ``` 3. 创建启动类,并在其中添加`@EnableSwagger2`注解。例如: ```java @SpringBootApplication @EnableSwagger2 public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 这样就完成了springboot整合swagger2 3.0.0版本的配置。你可以根据需要在项目中编写相应的接口文档注解以及其他相关配置。如果需要更详细的操作步骤和示例代码,你可以参考中提供的链接。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Springboot整合Swagger2(3.0.0版本)](https://blog.csdn.net/mo_sss/article/details/130820204)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Springboot整合Swagger UI 3.0.0 版本](https://blog.csdn.net/qq_42102911/article/details/126410050)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值