spring-boot integrate with swagger

1 篇文章 0 订阅
1 篇文章 0 订阅

Add below dependency in pom.xml

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.8</version>
</dependency>

Add the @EnableSwagger2 annotation to the Application class

@SpringBootApplication
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Applicataion.class, args);
    }
}

Key annotations of swagger

AnnotationComments
@ApiModelModel name like ‘User Model’
@ApiModelPropertyThe property description like ‘Name’, ‘Password’
@ApiThe API description like ‘User API’
@ApiOperationThe API method description like ‘Get User By Id’
@ApiImplicitParamsWill contains list of @ApiImplicitParam
@ApiImplicitParamthe parameter definition
@ApiResponsesContains list of @ApiResponse
@ApiResponsethe response definition

Sample for domain POJO

@ApiModel("User Model")
@AllArgsConstrcutor
@Getter
public class User {
    @ApiModelProperty("User ID")
    private int id;
    @ApiModelProperty("User Name")
    private String name;
    @ApiModelProperty("Password")
    private String password;
}

Note below annotations comes from lombok dependency
(Need IDE support lombok plugin)

AnnotationComments
@AllArgsConstrcutorIt will automatically generate the constructor
@NoArgsConstrcutorIt will automatically generate the constructor with empty parameters
@GetterIt will automatically generate the getterXX() method
@SetterIt will automatically generate the setXX() method
@Builderconvert the class to builder strategy
@DataContains @NoArgsConstrcutor @Setter @Getter and will override toString(),hashcode(),equals() methods

Sample for controller

@Api("User API")
@RestController
@RequestMapping("/user")
public class UserControll {
    @ApiOperation("Get the user by id")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="path",name="id",dataType="int",required=true,value="User ID",defaultValue="0")
    })
    @ApiResponses({
        @ApiResponse(code=403, message="Access forbidden"),
        @ApiResponse(code=404, message="Page not found")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable("id") int id) {
        return new User();
    }
}

Reference

《Java微服务实战》- 赵计刚

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值