swagger+springboot的整合与常用注解

与springboot整合

pom.xml

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>

配置类

SwaggerConfig.java

/**
 * @Description TODO swagger2配置类
 *
 * @author 
 * @email 
 * @date 
 */
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {
    /**
     * @Description TODO 配置资源路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/static/swagger/");
    }

    /**
     * @Description TODO 创建bean
     */
    @Bean
    public Docket createRestApi() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("Authorization").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());


        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            //加了ApiOperation注解的类,才生成接口文档
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            //包下的类,才生成接口文档
            .apis(RequestHandlerSelectors.basePackage("com.java"))
            .paths(PathSelectors.any()).build().globalOperationParameters(pars);
            //.securitySchemes(security());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("xxx管理平台")
            .description("接口文档")
            .termsOfServiceUrl("")
            .version("1.0.0")
            .build();
    }

    private List<ApiKey> security() {
        return newArrayList(
            new ApiKey("token", "token", "header")
        );
    }

}

启动类

添加@EnableSwagger2注解

如果配置类和启动类在同一级,注解写在配置类上也可以

swagger注解

控制层

类注解

@Api

放在 请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。

属性名称备注
valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径
position如果配置多个Api 想改变显示的顺序位置
produces如, “application/json, application/xml”
consumes如, “application/json, application/xml”
protocols协议类型,如: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true,将在文档中隐藏

方法注解

@ApiOperation

用在请求的方法上,说明方法的作用。 value="说明方法的作用" notes="方法的备注说明"

@ApiImplicitParams、@ApiImplicitParam

方法的参数的说明;@ApiImplicitParams 用于指定单个参数的说明

@ApiImplicitParams:用在请求的方法上,包含一组参数说明
	@ApiImplicitParam:对单个参数的说明	    
	    name:参数名
	    value:参数的汉字说明、解释
	    required:参数是否必须传
	    paramType:参数放在哪个地方
	        · header --> 请求参数的获取:@RequestHeader
	        · query --> 请求参数的获取:@RequestParam
	        · path(用于restful接口)--> 请求参数的获取:@PathVariable
	        · body(请求体)-->  @RequestBody User user
	        · form(普通表单提交)	   
	    dataType:参数类型,默认String,其它值dataType="Integer"	   
	    defaultValue:参数的默认值

示例

@Api(tags="用户模块")
@Controller
public class UserController {
	@ApiOperation(value="用户登录",notes="随边说点啥")
	@ApiImplicitParams({
		@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
		@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
		@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="int")
	})
	@PostMapping("/login")
	public JsonResult login(@RequestParam String mobile, @RequestParam String password,
	@RequestParam Integer age){
		//...
	    return JsonResult.ok(map);
	}
}

@ApiResponses、@ApiResponse

方法返回值的说明 ;@ApiResponses 用于指定单个参数的说明

@ApiResponses:方法返回对象的说明
	@ApiResponse:每个参数的说明
	    code:数字,例如400
	    message:信息,例如"请求参数没填好"
	    response:抛出异常的类

示例

@Api(tags="用户模块")
@Controller
public class UserController {

	@ApiOperation("获取用户信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query", name="userId", dataType="String", required=true, value="用户Id")
	}) 
	@ApiResponses({
		@ApiResponse(code = 400, message = "请求参数没填好"),
		@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
	}) 
	@ResponseBody
	@RequestMapping("/list")
	public JsonResult list(@RequestParam String userId) {
		...
		return JsonResult.ok().put("page", pageUtil);
	}
}

实体类

类注解

@ApiModel

用在JavaBean类上,说明JavaBean的 用途

@ApiModel:用于JavaBean的类上面,表示此 JavaBean 整体的信息
			(这种一般用在post创建的时候,使用 @RequestBody 这样的场景,
			请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )	

属性注解

@ApiModelProperty

用在JavaBean类的属性上面,说明此属性的的含议

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{

	@ApiModelProperty(value = "是否成功")
	private boolean success=true;
	@ApiModelProperty(value = "返回对象")
	private Object data;
	@ApiModelProperty(value = "错误编号")
	private Integer errCode;
	@ApiModelProperty(value = "错误信息")
	private String message;
		 
	/* getter/setter 略*/
}

访问

启动项目 http://localhost:xxxx/xxx/swagger-ui.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值