添加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>
model 描述 以及简单校验:
@ApiModel(description = "用户对象") @Data public class User { private int id; @NotNull(message = "name is notnull",groups = Group1.add.class) @ApiModelProperty(value="用户名",name="username",required = true) private String name; @NotNull(message = "age is notnull") @ApiModelProperty(value="年龄",name="username" ,required = true) private int age; @ApiModelProperty(value="备注",name="username") private String desc; }
通过注解描述接口以及添加@validated注解校验接口model:
@RestController @RequestMapping("/user") @Api(tags = {"用户操作接口"}) public class UserContorller extends BaseContorller { @ApiOperation("获取所有用户") @GetMapping("/user") public User getUserAll(){ User user = new User(); user.setId(1); user.setDesc("这是第一个用户"); user.setAge(18); user.setName("大兵"); return user; } @ApiOperation("根据用户id获取所有用户") @GetMapping(value = "/user/{id}") public User getUserById(@PathVariable("id") int id){ System.out.println(id); User user = new User(); user.setId(2); user.setDesc("这是第一个用户"); user.setAge(19); user.setName("大兵"); return user; } @ApiOperation("添加用户信息") @PostMapping("/user") public int saveUser(@RequestBody @ApiParam(value = "json/application",required = true) @Validated(Group1.add.class) User user){ System.out.println(user.toString()); return 1; }
最后配置Swagger2:
@Configuration @EnableSwagger2 //swagger注解,,开启 public class Swagger2Config { @Bean public Docket buildDocket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(buildApiInf()) .select() .apis(RequestHandlerSelectors.basePackage("com.test.swagger2.contorller")) .paths(PathSelectors.any()) .build(); } private ApiInfo buildApiInf(){ return new ApiInfoBuilder() .title("接口文档") // .description("springboot swagger2") /*.termsOfServiceUrl("http://blog.csdn.net/u014231523网址链接") .contact(new Contact("diaoxingguo", "http://blog.csdn.net/u014231523", "[email protected]"))*/ .build(); } //2.0以后使用ApiInfoBuilder().build(); @Bean public ApiInfo buildApiInfo(){ return new ApiInfoBuilder().build(); } }
访问http://localhost:8080/swagger-ui.html#!/ 效果如下: