需要如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
配置Swagger
package com.wu.parker.rest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.wu.parker"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("使用Swagger2构建RESTful APIs")
.version("1.0")
.build();
}
}
新建User.java,包括id,username,password属性,代码略。
新建CreateUserDto
package com.wu.parker.rest.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotBlank;
/**
* @author: wusq
* @date: 2018/12/5
*/
@ApiModel("新增用户参数")
public class CreateUserDto {
@ApiModelProperty("用户名")
@NotBlank(message = "用户名不能为空")
private String username;
@ApiModelProperty("密码")
@NotBlank(message = "密码不能为空")
private String password;
// get/set方法略
}
CreateUserDto用于从页面接收参数,并添加约束条件,比如哪些不能为空。
新建BaseResult工具类
package com.wu.parker.common.web;
import java.io.Serializable;
/**
* @author: wusq
* @date: 2018/12/5
*/
public class BaseResult implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code = 200;
private String message;
private Object data;
// get/set方法略
}
BaseResult用于controller封装数据,返回给页面,BaseResult有如下3个属性:
code表示状态码,实际使用时可以使用org.springframework.http.HttpStatus中的状态码,并扩展自定义的状态码;
message表示提示信息;
data表示结果数据。
UserController
package com.wu.parker.rest.controller;
import com.wu.parker.common.web.BaseResult;
import com.wu.parker.rest.dto.CreateUserDto;
import com.wu.parker.rest.po.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: wusq
* @date: 2018/12/5
*/
@Api(description = "用户服务")
@RestController
@RequestMapping("security/user/")
public class UserController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
@ApiOperation("新增")
@PostMapping("create")
public BaseResult create(@RequestBody @Validated CreateUserDto dto, BindingResult bindingResult){
BaseResult result = new BaseResult();
// 校验参数
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
log.error("新增用户参数错误:{}", fieldError.getDefaultMessage());
result.setCode(HttpStatus.BAD_REQUEST.value());
result.setMessage(fieldError.getDefaultMessage());
return result;
}
try {
User user = new User();
BeanUtils.copyProperties(dto, user);
log.info("接收到用户{},{}", user.getUsername(), user.getPassword());
result.setData(user);
} catch (Exception e) {
result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
result.setMessage(e.getMessage());
log.error("新增用户错误{}", e.getMessage());
e.printStackTrace();
}
return result;
}
}
测试
项目启动后,浏览器访问http://localhost:8080/swagger-ui.html即可打开Swagger页面,测试controller中的方法。
源代码
https://github.com/wu-boy/parker.git