swagger使用详解

swagger使用详解

一 swagger2依赖

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

二 swagger2配置

/**
 * Swagger2配置类
 * 在与spring boot集成时,放在与Application.java同级的目录下。
 * 通过@Configuration注解,让Spring来加载该类配置。
 * 再通过@EnableSwagger2注解来启用Swagger2。
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
	/**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     * 
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            	// 1.增加首页API相关信息
                .apiInfo(apiInfo()) 
            	// 2.设置要扫描的包路径
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
                // 3.对路径进行过滤
            	.paths(PathSelectors.any())
                .build();
    }
    
    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多请关注http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("sunf")
                .version("1.0")
                .build();
    }
}    

三 swagger注解使用

3.1 @Api和@ApiOperation

@Api用于描述Controller类

示例:

@Api(value = "users",tags = "系统权限 1-用户管理")
@RestController
@RequestMapping(value = "/users")
public class UserController extends BaseController {

}

用法:

tags:表示说明 
value:说明,可以使用tags替代 

@ApiOperation用于描述Controller类的方法

示例:

@ApiOperation(value="删除用户", httpMethod = "DELETE")
@RequestMapping(method = {RequestMethod.DELETE}, produces={"application/json;charset=UTF-8"})
public ResponseResult<?> deleteUser(@RequestParam Long[] ids) {}

用法:

value用于方法描述 
notes用于提示内容 
tags可以重新分组(视情况而用) 
3.2 @ApiModel和@ApiModelProperty

如果POJO类作为传入参数和返回数据时,如果使用此注解,则不需要再用3.3和3.4中的注解描述

@ApiModel用于描述POJO对象

示例:

@ApiModel(value="任务信息")
@Data
@TableName("sp_task")
public class SpTask implements Serializable{}

用法:

value	为模型提供备用名称
description	提供详细的类描述
parent	为模型提供父类以允许描述继承关系
discriminatory	支持模型继承和多态,使用鉴别器的字段的名称,可以断言需要使用哪个子类型
subTypes	从此模型继承的子类型数组
reference	指定对应类型定义的引用,覆盖指定的任何其他元数据

@ApiModelProperty用于描述POJO对象的属性

示例:

	 @ApiModelProperty(value="任务ID")
    private Long id;

    @ApiModelProperty(value="任务名")
    private String taskName;

用法:

value	属性简要说明
name	运行覆盖属性的名称。重写属性名称
allowableValues	限制参数可接收的值,三种方法,固定取值,固定范围
access	过滤属性,参阅:io.swagger.core.filter.SwaggerSpecFilter
notes	目前尚未使用
dataType	参数的数据类型,可以是类名或原始数据类型,此值将覆盖从类属性读取的数据类型
required	是否为必传参数,false:非必传参数; true:必传参数
position	允许在模型中显示排序属性
hidden	隐藏模型属性,false:不隐藏; true:隐藏
example	属性的示例值
readOnly	指定模型属性为只读,false:非只读; true:只读
reference	指定对应类型定义的引用,覆盖指定的任何其他元数据
allowEmptyValue	允许传空值,false:不允许传空值; true:允许传空值

3.3 @Apiparam和@ApiImplictParams和@ApiImplictParam

@Apiparam用于描述单个请求参数

@ApiOperation(value="删除用户", httpMethod = "DELETE")
@RequestMapping(method = {RequestMethod.DELETE}, produces={"application/json;charset=UTF-8"})
public ResponseResult<?> deleteUser(@ApiParam(required = true, value = "id") Long[] ids) {}

@ApiImplictParams用于描述请求对象参数,包含多个@ApiImplictParam

@ApiOperation(value="添加用户", httpMethod = "POST")
@ApiImplicitParams({
	@ApiImplicitParam(name = "userName", value = "用户名", required = true, paramType = "query", dataType = "String"),
	@ApiImplicitParam(name = "userPassword", value = "密码", required = true
})
@RequestMapping(method = {RequestMethod.POST}, produces={"application/json;charset=UTF-8"})
public ResponseResult<?> addUser(@RequestBody User user){}

@ApiImplictParam用于描述请求对象参数的属性

@ApiOperation(value="添加用户", httpMethod = "POST")
@ApiImplicitParams({
	@ApiImplicitParam(name = "userName", value = "用户名", required = true, paramType = "query", dataType = "String"),
	@ApiImplicitParam(name = "userPassword", value = "密码", required = true
})
@RequestMapping(method = {RequestMethod.POST}, produces={"application/json;charset=UTF-8"})
public ResponseResult<?> addUser(@RequestBody User user){}
3.4 @ApiResponses和@ApiResponse

@ApiResponses用于描述返回数据,包含多个@ApiResponse

这个不常用,略

@ApiResponse用于描述返回数据

这个不常用,略

四 与安全框架搭配

4.1 与SpringSecurity搭配

过滤器放行以下请求

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

配置过滤器链

<bean name="chainFilterBuff" class="com.nriat.shiro.ChainDefinitionSectionMetaSource">
      <property name="filterChainDefinitions">
         <value>

            <!--swagger文档-->
            /swagger**/** = anon
            /swagger-resources = anon
            /v2/** = anon
            /configuration/** = anon
            
         </value>
      </property>
   </bean>
4.3 通用配置

把swagger的静态资源路径映射到对应的目录META-INF/resources/下面

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个开源的Java开发框架,而Swagger是一个用于构建、发布、文档化和管理API的工具。下面详细介绍如何在Spring Boot中整合Swagger。 首先,你需要在pom.xml文件中添加Swagger的依赖项。在<dependencies>标签中添加以下代码: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.10.5</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.10.5</version> </dependency> ``` 然后,你需要在Spring Boot的配置类中添加相关的注解和配置。创建一个SwaggerConfig.java文件,添加以下代码: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("your.package.name")) .paths(PathSelectors.any()) .build(); } @Bean public UiConfiguration uiConfig() { return new UiConfiguration(null, "list", "alpha", "schema", UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L); } } ``` 在上面的代码中,你需要将"your.package.name"替换为你的应用程序的包名。这将扫描该包下的所有控制器,生成API文档。 接下来,你可以启动你的Spring Boot应用程序,并访问"http://localhost:8080/swagger-ui.html"来查看生成的API文档。你将看到所有的控制器和它们的方法以及相关的参数和注释。 如果你想修改API的文档信息,你可以使用Swagger中的注解来添加说明和标注。例如,你可以在控制器的方法上添加@ApiOperation注解来描述该方法的作用。 综上所述,将Swagger整合到Spring Boot中是很简单的。你只需要添加依赖项,配置SwaggerConfig类,然后访问Swagger UI来查看生成的API文档。同时,你可以使用Swagger注解来进一步完善API文档。希望这个教程可以帮助你理解如何在Spring Boot使用Swagger

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值