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
| Annotation | Comments |
|---|---|
| @ApiModel | Model name like ‘User Model’ |
| @ApiModelProperty | The property description like ‘Name’, ‘Password’ |
| @Api | The API description like ‘User API’ |
| @ApiOperation | The API method description like ‘Get User By Id’ |
| @ApiImplicitParams | Will contains list of @ApiImplicitParam |
| @ApiImplicitParam | the parameter definition |
| @ApiResponses | Contains list of @ApiResponse |
| @ApiResponse | the 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)
| Annotation | Comments |
|---|---|
| @AllArgsConstrcutor | It will automatically generate the constructor |
| @NoArgsConstrcutor | It will automatically generate the constructor with empty parameters |
| @Getter | It will automatically generate the getterXX() method |
| @Setter | It will automatically generate the setXX() method |
| @Builder | convert the class to builder strategy |
| @Data | Contains @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微服务实战》- 赵计刚

博客介绍了在Java中使用Swagger的相关内容,包括在pom.xml添加依赖、在Application类添加@EnableSwagger2注解,还给出了Swagger关键注解,以及领域POJO和控制器的示例,同时提到参考书籍《Java微服务实战》。
995

被折叠的 条评论
为什么被折叠?



